lua-users home
lua-l archive

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

Benoit Germain wrote:
> 2011/6/24 Mike Pall <>:
> > The only portable solution would be to identify the internal
> > function in one state and then pick the same function in another
> > state, e.g. by using an inverted table in both states.
> All right, but how can I do this when LuaJIT's lua_tocfunction returns
> NULL for these functions? How can I differentiate them? Is there
> anything else than a string "fast#NN" in the lua_Debug structure?

Err, no. You use the internal function as a key into a table.

Proof-of-concept code:

  -- Generate an inverted table for a module (or several modules):
  local invmath = {}
  for k,v in pairs(math) do
    invmath[v] = k

  -- Suppose we want to copy this function:
  local func = math.abs

  -- Look up the function in the original state and get its name:
  local name = invmath[func]
  print(name) --> "abs"

  -- Now copy the function name (and module id) to the target state.

  -- Finally look up the function name in the target state:
  local newfunc = math[name]
  print(newfunc) --> function: fast#37
  print(newfunc(-1)) --> 1

You'll probably want to generalize this and merge multiple modules
into a single inverted table. The values need to indicate the module,
too. E.g. use "\001abs" for 'math.abs', "\001sqrt" for 'math.sqrt'
or "\002sub" for 'string.sub' and so on. That way you don't need a
forward lookup table in the target state, only a linear list of the
module tables for the standard modules.