我编写了一个C程序并在其中编写了以下两个函数
1. int c_add(lua_State* L)
{...some code here...
}
2. int main(int argc, char* argv)
{...some code here...
lua_register(L, "c_add", c_add);
}
并通过以下命令成功编译它。
gcc -o test.exe test.c -I /home/ec2-user/install/lua-5.1.5/src -llua-5.1
但是使用lua程序调用后出现如下错误。
lua: func2.lua:2: attempt to call global 'c_add' (a nil value)
如何解决这个问题?`
最佳答案
您需要将代码编译为共享库,以便从外部 Lua 实例访问 C 函数。您不需要 main
函数,而是将 -shared
标志传递给 gcc。然后你需要通过实现以下函数让Lua知道当 require
被调用时要做什么:
// same name as the so/dll
// v
LUALIB_API int luaopen_test(lua_State *L) {
lua_register(L, "c_add", c_add);
return 0;
}
这将创建一个单一的全局函数。最好使用 luaL_register
注册一个 luaL_Reg
函数数组:
static const luaL_Reg function_list[] = {
{"c_add", c_add},
{NULL, NULL}
};
LUALIB_API int luaopen_test(lua_State *L) {
luaL_register(L, "test", function_list);
return 1;
}
这样 require
返回一个函数表:
local my_c_functions = require("test")
print(my_c_functions.c_add(42, 42))
关于lua - 使用Lua调用C(Linux中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53863054/