Lua: How to reference a lua method inside a lua class from C for later use?
I get a reference to a lua method which is inside a class with the funcion luaL_ref. When I want to call that metho开发者_StackOverflow中文版d I use the function lua_rawgeti to push the function into the stack and then I use lua_pcall to actually call the method.Everithing works fine except that I cannot acces other class members from the method because self is nil.
Does anyone know how can I fix this ?
Thank you!
Lua "methods" are actually functions. They have no notion of self
like in other languages. Like gwell says, the obj:method(...)
is actually syntactic sugar for obj.method(obj, ...)
.
If you need to work with objects, don't save references to object functions - save the reference to object itself. You can use the following code to call a method using Lua C API:
/* get the object, idx is the identifier returned by luaL_ref */
lua_rawgeti(L, LUA_REGISTRYINDEX, idx);
lua_getfield(L, -1, "method");
/* push parameters - the object first, then the rest, then call the function */
lua_pushvalue(L, -2);
...
lua_call(L, nParams + 1, 1);
The Lua colon operator uses syntactic sugar to place the table being referenced as the first parameter (a.k.a. self
) in a function call. You should be able to put the table (object) as the first parameter to the function call and it should fix your problem.
精彩评论