嗯,将C函数作为函数成员推送或使用lua_register(L, lua_func_name, c_func);将C函数注册为Lua函数没有问题。
但是如何告诉Lua我想将luaFoo()作为C中"foober"的回调参数呢?
lua_pushcfunction - 推送C函数,lua_pushstring仅推送普通字符串,因此回调字段成为字符串而不是函数。
Lua代码:
CALLBACKS = {};
FOO = 0;
function luaFoo()
FOO = FOO + 1;
end;
function addCallback(_name, _callback)
CALLBACKS[_name] = _callback;
end;
function doCallback(_name)
CALLBACKS[_name]();
end;
C 代码:
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);
如果我得到已经在lua_register中注册的C函数,如何将它们作为回调参数从C传递。因此,我们注册c_foo => c_foo存在作为lua函数,如何告诉我们想要将"c_foo"作为回调函数参数传递。