View Single Post
05/05/14, 07:08 AM   #2
LilBudyWizer
AddOn Author - Click to view addons
Join Date: Apr 2014
Posts: 32
One way is to hook the function. LibAddonMenu uses Prehook defined by the api. Writing your own hook is pretty simple, you just use a closure. A closure is a function that returns a function and has local variables used by that returned function. A simple example is:

Lua Code:
  1. function GetPrint(text)
  2.     local text = text
  3.     return function () print(text) end
  4. end
  5.  
  6. PrintHello = GetPrint("Hello")
  7. PrintHello()

GetPrint returns a function that prints whatever text you passed to GetPrint. The actual parameter will be gone when that returned function executes, but the local will still be there. So hooking a function is simply:

Lua Code:
  1. function Hook(funcname, before, after)
  2.     local origfunc = _G[funcname]
  3.     local before = before
  4.     local after = after
  5.     return function ( ... )
  6.         before( ... )
  7.         local parms = {origfunc( ... )}
  8.         after( ... )
  9.         return unpack(parms)
  10. end
  11.  
  12. function mybefore( ... )
  13.     print("hello")
  14. end
  15.  
  16. function myafter( ... )
  17.     print("world")
  18. end
  19.  
  20. SomeFunc = Hook("SomeFunc", mybefore, myafter)

There's a lot of possible variations on that depending upon what, exactly, you're wanting to do. As an example you could use before to modify parms in which case you would pass it's return value as the parameters to the original function. Similarly after could modify results from the original function. So:

Lua Code:
  1. return after(origfunc(before(...)))

You could also skip calling the original when it's called with particular parameters. The main caveat is be sure the hook can handle being called while the hook is executing. The function you hook may call itself as well as your code directly or indirectly calling it.
  Reply With Quote