lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

> In another different file I should have one list (I still don't know how
> to make this list. It has to be in a generic way to be used for any
> program just changing the list) of the functions that I want to 
> (for example, the query and remove). Before or after the execution of
> them, it must execute the function logging and then return to execute 
> next function.

You will want to use the "reflexive debug interface", as described
in the manual. Set a hook function to intercept on call and return, and
then try to identify the function that is being intercepted.

If your functions are globals, it is not too difficult.


  local intercepts = {}

  function intercept(f, on)
    local rv = intercepts[f]
    intercepts[f] = on
    return rv
  local hookstack = {n = 0}

  local function callhook()
    local f = debug.getinfo(3, "f").func
    table.insert(hookstack, f)
    if intercepts[f] then doOnCall(f) end

  local function rethook()
    local f = table.remove(hookstack)
    if intercepts[f] then doOnReturn(f) end

  local case = {
    ["call"] = callhook,
    ["return"] = rethook,
    ["tail return"] = rethook
  local function nothing() end

  local function myhook(what)
    (case[what] or nothing)()

  debug.sethook(myhook, "cr")

-- define doOnCall and doOnReturn to do whatever
-- to intercept a function:

function foo(a) print "foo" end
intercept(foo, true)

-- to intercept a function given its name (if it is a global)
a = "foo"
intercept(getfenv()[a], true)

-- I hope the above code is easy to follow.
-- Quick test:

> function doOnCall(func) print "An intercepted call" end
> function doOnReturn(func) print "An intercepted return" end
> foo(3)
An intercepted call
An intercepted return