title: How to patch or replace a function in Lua (with ability to restore)
body: <p>I think I have missed something in the code, either my "pseudo-code" is not correct or functions are not passed by reference in Lua..<br>
  I just want a small library that allows me to patch/replace a function with another function, but with ability to restore back the patched function to its original one.<br>
  <br>
  Perhaps, somebody have made such library already in the past (I just can't find it).<br>
  <br>
  My current code:</p>
  
  <pre><code>--[[
  When user wants to patch/replace/detour a variable of type "function" to equal to another variable of type "function", we should always first check user's input, that is the following question - have user supplied valid arguments.
  If invalid argument is caught, then throw an error to the user.
  Now we know that user have supplied valid arguments, next we should check if supplied function (that is to be patched) is already patched function, if it is then throw an error to the user.
  Now we save supplied function (the one to be patched) in a global table (to allow user to restore it later using another function).
  Finally, we assign a function (the one to be patched) to the second function that user have supplied.
  
  
  When user wants to restore original function, we should again check user's input first, that is, have user supplied a function and if so - is it really patched.
  Now we know that user have supplied valid argument, so lets restore original function by looking-up in a global table (where we saved original function).
  If by any chance original function is not found, just throw an error to the user.
  We have all information at this point, assign a patched function (from user's input) to the original function.
  Finally, clean-up, remove original function information from our global table (as it is no longer patched).
  --]]
  
  ftbl = ftbl or {}
  
  patchf = function(dest, src)
      assert(type(dest) == "function", "bad argument #1 (function expected, got " .. type(dest) .. ")")
      assert(type(src) == "function", "bad argument #2 (function expected, got " .. type(src) .. ")")
      assert(not ftbl[src], "destination is already patched/same source exists")
      ftbl[src] = dest
      dest = src
  end
  
  restoref = function(src)
      assert(type(src) == "function", "bad argument #1 (function expected, got " .. type(src) .. ")")
      assert(type(ftbl[src]) == "function", "source is not patched/source does not exists")
      fsrc = ftbl[src]
      ftbl[src] = nil
  end
  
  local my_function = function()
    print("Hello from my_function :D", 1)
  end
  
  local another_function = function()
    print("Hello from another_function D:", 2)
  end
  
  patchf(another_function, my_function)
  
  another_function() -- Hello from another_function D:    2
  </code></pre>
  
  <p>As you can see, it didn't patched another_function with my_function.</p>