'Attempt to index a string value' error while loading a c++ module in lua
我正在尝试使用lua中用C编写的函数。下面给出的是cpp文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | extern"C" { #include"lua.h" #include"lauxlib.h" #include"lualib.h" } static int add_5(lua_State *L) { double d = lua_tonumber(L, 1); /* get argument */ d=d+5; lua_pushnumber(L, d); /* push result */ return 1; /* number of results */ } static const struct luaL_Reg mylib [] = { {"add_5", add_5}, {NULL, NULL} /* sentinel */ }; extern"C" { int luaopen_mylib (lua_State *L) { //luaL_newlib(L, mylib); luaL_register(L, NULL, mylib); return 1; } } |
我使用以下命令通过g编译了以上代码:
1 | g++ -shared -o mylib.so test.cpp -fPIC |
我在lua解释器上遇到以下错误:
1 2 3 4 5 6 7 8 | Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio > local temp = require"mylib" attempt to index a string value stack traceback: [C]: ? [C]: in function 'require' stdin:1: in main chunk [C]: ? |
请注意,由于某些原因,我无法升级Lua的版本。
请注意,LHF建议不要这样做,因为它会自动将库的表放入全局表中,而库的用户可能只希望将其作为局部变量使用。另一种方法是在调用