准备工作
# apt-get install lua5.1 liblua5.1-0-dev
因为想移植到LEDE/OpenWRT, 所以选择了 lua 5.1版本
上代码
#include "stdio.h" #include "lua5.1/lauxlib.h" #include "lua5.1/lualib.h" static int add2(lua_State* L) { double op1 = luaL_checknumber(L,1); double op2 = luaL_checknumber(L,2); lua_pushnumber(L,op1 + op2); return 1; } static int sub2(lua_State* L) { double op1 = luaL_checknumber(L,1); double op2 = luaL_checknumber(L,2); lua_pushnumber(L,op1 - op2); return 1; } const char* testfunc = "print(add2(1.0,2.0)) print(sub2(20.1,19))"; int main() { lua_State* L = luaL_newstate(); luaL_openlibs(L); lua_register(L, "add2", add2); lua_register(L, "sub2", sub2); if (luaL_dostring(L,testfunc)) { printf("Failed to invoke.\n"); } lua_close(L); return 0; }
编译
gcc test.c -llua5.1 -o luatest
运行
./luatest 3 1.1
反过来, C做扩展库,让lua调用
#include "stdio.h" #include "lua5.1/lauxlib.h" #include "lua5.1/lualib.h" static int add(lua_State* L) { double op1 = luaL_checknumber(L,1); double op2 = luaL_checknumber(L,2); lua_pushnumber(L,op1 + op2); return 1; } static int sub(lua_State* L) { double op1 = luaL_checknumber(L,1); double op2 = luaL_checknumber(L,2); lua_pushnumber(L,op1 - op2); return 1; } static luaL_Reg mylibs[] = { {"add", add}, {"sub", sub}, {NULL, NULL} }; int luaopen_mytestlib(lua_State* L) { const char* libName = "mytestlib"; luaL_register(L, libName, mylibs); return 1; }
编译成so库
gcc testlib.c -fPIC -shared -o mytestlib.so
test.lua
require "mytestlib" print(mytestlib.add(1.0, 2.0)) print(mytestlib.sub(20.1, 19))
运行
lua test.lua 3 1.1
本站的文章和资源来自互联网或者站长的原创,按照 CC BY -NC -SA 3.0 CN协议发布和共享,转载或引用本站文章应遵循相同协议。如果有侵犯版权的资 源请尽快联系站长,我们会在24h内删除有争议的资源。欢迎大家多多交流,期待共同学习进步。