Hooking in

SethbeastalanSethbeastalan Join Date: 2011-05-05 Member: 97360Members
I'm a C++/Java programmer mainly, so I'm trying to pick up Lua for the first time right now. It isn't too different, but one thing that I've been hearing about on these forums, but can't find much information on is 'hooking.' Apparently that's how you overwrite the source code without actually overwriting it (so you can still play the game normally, and so your work isn't lost when it updates).

I really don't know how this works, and was wondering where to look for more info, or if you could just tell me if it's only a few sentences.

Comments

  • RioRio Join Date: 2005-01-28 Member: 38716Members
    edited March 2013
    Hooking is just a fancy name for overwriting already defined Lua functions, extend them and call the original functions again. Lua functions can be assigned to variables and can also be simply redefined. That's why you can do something like this:
    // NS2 function we want to hook (this is just for the example, you don't need to specify the function)
    function GetFriendlyFire()
    [...]
    end
    
    // Hook the function and assign it to a variable called oldGetFriendlyFire so we can still call it later
    local oldGetFriendlyFire = GetFriendlyFire
    // Now you just need to redeclare the original function
    function GetFriendlyFire()
       // ... and call the original function again (if the function had parameters, you can just pass them)
       oldGetFriendlyFire()
    
       // new code here
    end
    

    If you want to hook into a table method, it pretty much looks the same:
    // NS2 method we want to hook
    function NS2Gamerules:CheckGameEnd()
    [...]
    end
    
    // Assign the method to a variable (notice the period instead of the colon)
    local ns2GamerulesCheckGameEnd = NS2Gamerules.CheckGameEnd
    // Redeclare the method
    function NS2Gamerules:CheckGameEnd()
       // ... and call the old method with the current table!
       ns2GamerulesCheckGameEnd(self)
    
       // new code here
    end
    

    That's how you would extend a function. If you want to overwrite it, just don't call the original function.
    You might hear the terms pre- and post-hooks, which define where you call the original function. Pre-hooks call the original function after your additional code and post-hooks call the original function before your additional code (like in the example above).
  • SethbeastalanSethbeastalan Join Date: 2011-05-05 Member: 97360Members
    Thanks so much for the fast response.
Sign In or Register to comment.