main.cpp
int lua_cb = LUA_REFNIL; int lua_cb_arg = LUA_REFNIL; int setcb(lua_State *L) { lua_pushvalue(L, -2); lua_callback = luaL_ref(L, LUA_REGISTRYINDEX); lua_pushvalue(L, -1); lua_cb_arg = luaL_ref(L, LUA_REGISTRYINDEX); return 0; } int main() { lua_State* L = luaL_newstate(); top = lua_gettop(L); luaopen_base(L); luaL_openlibs(L); //注册回调 lua_register(L, "setcb", setcb); int ret = luaL_dofile(L, "test.lua"); if(ret != 0) { printf("%s", lua_tostring(L, -1)); } //调用回调 lua_rawgeti(L, LUA_REGISTRYINDEX, lua_cb ); lua_rawgeti(L, LUA_REGISTRYINDEX, lua_cb_arg); lua_call(L, 1, 0); lua_close(L); getchar(); return 1; }
test.lua
local cb_arg = {a=1}; setcb(function(_arg) print("cb' s arg is a table, arg.a=" .. _arg["a"]); end, cb_arg);