使用Lua调用C(在Linux中)

使用Lua调用C(在Linux中),lua,Lua,我编写了一个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/i

我编写了一个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\u寄存器注册
luaL\u 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))

文件
func2.lua
是什么?您是如何运行它的?@cyclamilist谢谢您的回复。代码在这里
--func2.lua
打印(c_添加(3,4))
@cyclaminit,我通过
lua func2运行它。lua
lua.exe
不是
test.exe
。您拥有由
test.exe
中的代码定义的
c\u add
函数,因此必须从
test.exe
中运行
func2.lua
,谢谢。我现在对此有了更深的理解。但是当我使用上面的代码时,出现了一个新的错误
lua:从文件'/usr/local/lib/lua/5.3/test.so'加载模块'test'时出错:
/usr/local/lib/lua/5.3/test.so:未定义的符号:luaL\u寄存器
是否意味着我必须在C程序中包含come库?
luaL\u寄存器
来自lua 5.1。在LUA5.3中,
luaL\u寄存器
没有定义,除非您在编译Lua时定义了
Lua\u COMPAT\u模块
,因此如果您是为LUA5.3编译库,最好将
luaL\u寄存器(L,“test”,function\u list)
替换为
luaL\u newlib(L,function\u list)
(并确保您使用的是Lua标头的Lua 5.3版本)@cyclaminit感谢您的详细解释。我已按照您的建议替换了该函数,但出现了下一个错误。
lua:从文件'/usr/local/lib/lua/5.3/test.so'加载模块'test'时出错:
/usr/local/lib/lua/5.3/test.so:未定义的符号:luaopen\u test
但没有“luaopen\u test”在我的源代码中。正如PaulR在上面解释的那样,当您
需要从Lua调用库时,您的库需要Lua VM调用一个函数。在这种情况下,函数需要命名为
luaopen\u test
。有关更多信息,请参阅文档。