基于前文《C++调用Lua》继续探索Lua调用C++函数的问题:
test_lua_call_cpp.cpp文件:
#include <stdio.h>
extern "C"{
#include "lua.h"
#include "lualib.h"
#include "luaxlib.h"
};
lua_State* L;
//这个函数将被Lua调用
static int average(lua_State *L)
{
//得到Lua函数传入的参数个数
int n = lua_gettop(L);
double sum = 0;
int i;
for (i = 1; i <= n; i++)
{
sum += lua_tonumber(L,i);
}
//向解释器的值栈中压入结果值
lua_pushnumber(L,sum / n);
lua_pushnumber(L,sum);
//指明返回参数有两个
return 2;
}
int main(int argc,char *argv[])
{
L = luaL_newstate();
luaopen_base(L);
luaL_openlibs(L);
luaL_loadfile(L,"add.lua");
lua_pcall(L,LUA_MulTRET,0);
//向解释器注册C++函数
lua_register(L,"cpp_average",average);
lua_getglobal(L,"cppGetAverageAndSum");
lua_pushnumber(L,10);
lua_pushnumber(L,20);
lua_pushnumber(L,30);
lua_pushnumber(L,40);
lua_call(L,4,2);
int sum = (int)lua_tonumber(L,-1);
lua_pop(L,1);
int avg = (int)lua_tonumber(L,1);
printf("Cpp Output The avg is %d\n",avg);
printf("Cpp Output The sum is %d\n",sum);
lua_close(L);
getchar();
return 0;
}
add.lua文件:
function add(x,y)
return x + y
end
function cppGetAverageAndSum(w,x,y,z)
avg,sum = cpp_average(w,z)
print("Lua Output The average is ",avg)
print("Lua Output The sum is ",sum)
return avg,sum
end
运行结果:
总结以上是内存溢出为你收集整理的Lua调用C++全部内容,希望文章能够帮你解决Lua调用C++所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)