c++代码// testlib.cpp
#include <iostream>
#include <lua.hpp>
using namespace std;
/* 定义C++的Average 函数 */
int average(lua_State *L)
{
int num = lua_gettop(L); //获取参数个数
double sum = 0;
double avg = 0;
for(int i = 1; i <= num; i++) //注意Lua栈下标从1开始
{
sum += lua_tonumber(L, i); //求和
}
avg = sum / num; //求平均
lua_pushnumber(L, avg); //平均值入栈
lua_pushnumber(L, sum); //和入栈
int size = lua_gettop(L);
for(int i=1;i<=size;i++)
{
printf("[%d] = %f
",i, lua_tonumber(L, i));
}
return 2; //return 返回值个数
}
/* 定义C++的sub函数 */
int sub(lua_State *L)
{
int num = lua_gettop(L);
if(num != 2)
{
cout << "Input param number is not correct!" << endl;
return 0;
}
int a = lua_tonumber(L, 1); //获取第一个参数,被减数
int b = lua_tonumber(L, 2); //获取第二个参数,减数
int diff = a - b;
lua_pushnumber(L, diff); //结果压入栈
return 1;
}
/* 定义C++的add函数 */
int add(lua_State *L)
{
int num = lua_gettop(L);
if(num != 2)
{
cout << "Input param number is not correct!" << endl;
return 0;
}
int a = lua_tonumber(L, 1); //获取第一个参数,被减数
int b = lua_tonumber(L, 2); //获取第二个参数,减数
int sum = a + b;
lua_pushnumber(L, sum); //结果压入栈
return 1;
}
//使用luaL_Reg注册新的C函数到Lua中
static const luaL_Reg test_functions[] =
{
{"average", average},
{"add", add},
{"sub", sub},
{NULL, NULL} //数组中最后一对必须是{NULL, NULL},用来表示结束
};
/* luaopen_XXX,XXX为库名称,若库名称为testlib.so,XXX即为testlib */
//luaopen_testlib函数前要加上 extern "C" 导出函数名才能被lua调用
//要不然在lua require的时候会报错找不到luaopen_testlib
extern "C" int luaopen_testlib(lua_State *L)
{
luaL_newlib(L, test_functions); //Lua 5.2之后用luaL_newlib代替了luaL_register
return 1;
}
makefile
testlib.so: testlib.h testlib.cpp g++ -std=c++11 -shared -fPIC testlib.cpp -o testlib.so -I /usr/local/include/lua -l lua -l dl clean: rm -f testlib.so
注:
-I /usr/local/include/lua ---> 指明要链接的lua头文件的路径
-l lua -l dl. 参考https://www.cnblogs.com/cy163/archive/2009/03/12/1409434.html,https://blog.csdn.net/qq_32534441/article/details/90552130?spm=1035.2023.3001.6557&utm_medium=distribute.pc_relevant_bbs_down.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-1.nonecase&depth_1-utm_source=distribute.pc_relevant_bbs_down.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-1.nonecase
在执行make命令之前需要利用lua源码编译出静态库(.a)或者动态库(.so)放在同级目录下,
要不然在执行make编译testlib.so时会报很多lua接口函数找不到
lua调用
local abc = require("testlib")
avg,sum = abc.average(100, 200, 300, 400, 500)
diff = abc.sub(100,50)
total = abc.add(100,50)
print("avg = ",avg)
print("sum =",sum)
print("diff = ",diff)
print("total = ",total)