作者:_流星_123 | 来源:互联网 | 2023-06-05 13:11
1.函数注册Lua5.4.4变化比较大,从5.2后就变了staticvoidmy_fun(lua_State*lua){constintarg1luaL_chec
1. 函数注册
Lua 5.4.4 变化比较大,从5.2后就变了
static void my_fun(lua_State* lua) {const int arg1 = luaL_checkinteger(lua, 1);const char* str= luaL_checklstring(lua, 2, NULL);printf("%d : %s\r\n",arg1, str);
}static const luaL_Reg DRIVERS[] = {{"my_fun", my_fun}
};static int reg_funcs(lua_State* L) {int i;for (i &#61; 0; i < sizeof(DRIVERS) / sizeof(luaL_Reg); &#43;&#43;i) {lua_pushcfunction(L, DRIVERS[i].func);lua_setglobal(L, DRIVERS[i].name);}return LUA_OK;
}
这样在lua脚本中就可以调用了
my_fun(1, "Hello from Lua");
2. 注册模块
int my_func1(lua_State* L)
{
}int my_func2(lua_State* L){
}
static const luaL_Reg my_funcs[] &#61; {{"func1", my_func1},{"func2", my_func2},{NULL, NULL}
};
在嵌入式系统中可以自己写函数优化一下了&#xff0c;这里用NULL对象来表示结束有点儿浪费资源
int lua_openMyLib( lua_State* L) {luaL_newlib(L,my_funcs);return 1;
}
然后在初始化时添加
luaL_requiref(L, "my", lua_openMyLib, 1);
5.2之后不能用lua_register了。这样在Lua脚本中就可以这样用&#xff1a;
my.func1();
my.func2();
还是喜欢这样的代码&#xff0c;看着舒服&#xff0c;不喜欢用下划线以及很长的函数名。