Lua - References to Functions Within Tables
문제
If I have a global table Table
that has functions getValue()
, setValue()
, etc. Can I store a reference to Table.getValue
or do I have to store a reference to Table
and then call the member functions?
lua_getglobal(L, "Table");
lua_getfield(L, -1, "getValue");
getValueRef = luaL_ref(L, LUA_REGISTRYINDEX);
lua_getfield(L, -1, "setValue");
setValueRef = luaL_ref(L, LUA_REGISTRYINDEX);
lua_pop(L, 1); // Pop "Table" off of the stack
해결책
There is no such thing as a "member function" in Lua. There is simply a function, which is a value. You can store functions anywhere, directly in the global table, in some other table you create, etc. Functions (and all Lua values for that matter) have no association with any table they happen to be stored in.
If you want to store a function somewhere (and creating a "reference" is nothing more than storing it somewhere), you can.
FYI: it is not a good idea to directly use the registry for Lua "references". I'd suggest creating a table you store in a particular slot in the registry to use for your references. Of course, I would say that it's not a good idea to use "references" for what you're doing period.
다른 팁
You can always create a "bound" function as a closure:
local tbl=Table
local function TableGetValue(key)
return tbl:getValue(key)
end
do_stuff_with(TableGetValue)