朋友寫的例子,先保存這里身隐,回頭也許需要廷区。
cpptest.lua
local mylib = require "mylib"
print(mylib.add(10))
[root@dev1 lua]# cat mylib.cpp
#include <iostream>
using namespace std;
#ifdef __cplusplus
extern "C"
{
#endif
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
int luaopen_mylib(lua_State*);
#ifdef __cplusplus
}
#endif
int add(lua_State *state)
{
int n = lua_gettop(state);
int sum = 0;
for (int i = 0; i < n; ++i)
{
sum += lua_tonumber(state, i+1);
}
if (n != 0)
{
lua_pushnumber(state, sum);
return 1;
}
return 0;
}
const luaL_Reg lib[] =
{
{"add", add},
{nullptr, nullptr}
};
int luaopen_mylib(lua_State *state)
{
luaL_register(state, "mylib", lib);
return 1;
}
[root@dev1 lua]# lua cpptest.lua
10
C++的例子
[root@dev1 test2]# ll
總用量 24
-rw-r--r--. 1 root root 69 10月 19 23:44 cpptest.lua
-rw-r--r--. 1 root root 1685 10月 19 23:42 mylib.cpp
-rwxr-xr-x. 1 root root 14224 10月 19 23:42 TestLua.so
[root@dev1 test2]# cat cpptest.lua
require "TestLua"
c = TestLua()
print("add x + y = " .. c:cadd(4,5))
[root@dev1 test2]# cat mylib.cpp
#include <iostream>
using namespace std;
#ifdef __cplusplus
extern "C"
{
#endif
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
int luaopen_TestLua(lua_State*);
#ifdef __cplusplus
}
#endif
int add(lua_State *state)
{
int n = lua_gettop(state);
int sum = 0;
for (int i = 0; i < n; ++i)
{
sum += lua_tonumber(state, i+1);
}
if (n != 0)
{
lua_pushnumber(state, sum);
return 1;
}
return 0;
}
class TestLua
{
public:
TestLua() {}
virtual ~TestLua() {}
int cadd(int x, int y)
{
cout << "x + y = " << (x+y) << endl;
return x + y;
}
};
static int createTestLua(lua_State *state)
{
*(TestLua**)lua_newuserdata(state, sizeof(TestLua*)) = new TestLua();
luaL_getmetatable(state, "TestLua");
lua_setmetatable(state, -2);
return 1;
}
static int destroyTestLua(lua_State *state)
{
delete *(TestLua**)lua_topointer(state, 1);
return 0;
}
static int callAdd(lua_State *state)
{
TestLua *pT = *(TestLua**)lua_topointer(state, 1);
lua_pushnumber(state, pT->cadd(lua_tonumber(state, 2), lua_tonumber(state, 3)));
return 1;
}
int luaopen_TestLua(lua_State *state)
{
lua_pushcfunction(state, createTestLua);
lua_setglobal(state, "TestLua");
luaL_newmetatable(state, "TestLua");
lua_pushstring(state, "__gc");
lua_pushcfunction(state, destroyTestLua);
lua_settable(state, -3);
lua_pushstring(state, "__index");
lua_pushvalue(state, -2);
lua_settable(state, -3);
lua_pushstring(state, "cadd");
lua_pushcfunction(state, callAdd);
lua_settable(state, -3);
lua_pop(state, 1);
return 1;
}
[root@dev1 test2]# lua cpptest.lua
x + y = 9
add x + y = 9
遇到的錯(cuò)誤
[root@dev1 test2]# gcc -Wall -shared -fPIC -o ]TestLua.so -I/usr/local/openresty/luajit/include/luajit-2.1/ -L/usr/lib64/ -llua-5.1 mylib.cpp
解決辦法
The problem is most likely caused by a missing libstdc++.so.6 on your machine.
Check if you have libstdc++.so.6 on your machine using .
find /usr/ -name libstdc++.so.6
If not, then you should be able to install it using: apt-get install libstdc++6