The push lua function as a table element from the C API

Well there is no problem to push the C function as a member of a function or to execute the C function as a lua function with lua_register (L, lua_func_name, c_func);

But how to tell lua that I want to pass luaFoo () as a function callback parameter for "foober" from C? lua_pushcfunction - pushes the C function, lua_pushstring pushes only a simple string, so the callback field becomes a string, not a function.

Lua Code:

CALLBACKS = {}; FOO = 0; function luaFoo() FOO = FOO + 1; end; function addCallback(_name, _callback) CALLBACKS[_name] = _callback; end; function doCallback(_name) CALLBACKS[_name](); end; 

C code:

 static int c_foo(lua_State* l) { printf("FOO\n"); return 0; } /*load lua script*/; lua_State* l = /*get lua state*/; lua_getglobal(l, "addCallback"); lua_pushstring(l, "foober"); //What push for luaFoo() lua_pushcfunction(l, c_foo); lua_call(l, 2, 0); lua_getglobal(l, "doCallback"); lua_pushstring(l, "foober"); lua_call(l, 1, 0); 

Similiar - if I get C functions that are already registered with lua_register , how to pass them as a callback parameter from C. So we register c_foo => c_foo as a lua function, how to say that we want to pass "c_foo" as a funck parameter funck.

+4
source share
1 answer

Remember, that:

 function luaFoo() ... end 

equivalent to this, in Lua:

 luaFoo = function() ... end 

So your question ultimately boils down to this: "I have a value in the global table. How do I push it onto the stack?" The fact that this value is a function does not matter; the value of a function in Lua is no different from an integer value that is no different from a string value. Obviously, you can do different things with them, but you just want to copy them. This works the same regardless of value.

The function you are looking for is lua_getglobal .

Regarding the second question, you can do this in one of two ways. You can either get the function value registered in the global table, or simply reregister it with lua_pushcfunction . Since you are not using upvalues, re-registering it actually has no drawbacks.

Oh, and one more thing in code style. Lua does not require ; at the end of the instructions. You can do this (to make C-native programmers feel more comfortable), but this is not necessary.

+6
source

All Articles