lua和C通過虛擬棧這種交互方式簡單而又可靠,缺點就是C做棧平衡稍微會多寫一點代碼。 今天分享學到的C模塊回調Lua函數(shù)的兩種方法,都是炒冷飯,大俠勿噴。
static int lua_callback = LUA_REFNIL;
static int setnotify(lua_State *L)
{
lua_callback = luaL_ref(L, LUA_REGISTRYINDEX);
return 0;
}
static int testnotify(lua_State *L)
{
lua_rawgeti(L, LUA_REGISTRYINDEX, lua_callback);
lua_call(L, 0, 0);
}
function callback( )
print "Callback"
end
cb.setnotify(callback)
cb.testnotify()
3. 完整例子
cb.c
#include stdio.h>
#include stdlib.h>
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
static int lua_callback = LUA_REFNIL;
static int setnotify(lua_State *L)
{
lua_callback = luaL_ref(L, LUA_REGISTRYINDEX);
return 0;
}
static int testnotify(lua_State *L)
{
lua_rawgeti(L, LUA_REGISTRYINDEX, lua_callback);
lua_call(L, 0, 0);
}
static int testenv(lua_State *L)
{
lua_getglobal(L, "defcallback");
lua_call(L, 0, 0);
}
static const luaL_Reg cblib[] = {
{"setnotify", setnotify},
{"testnotify", testnotify},
{"testenv", testenv},
{NULL, NULL}
};
int luaopen_cb(lua_State *L)
{
luaL_register(L, "cb", cblib);
return 1;
}
require("cb")
function callback( )
print "Callback"
end
function defcallback()
print "Predef callback"
end
cb.setnotify(callback)
cb.testnotify()
print "Done"
cb.testenv()