先安装lua,安装完后会有个include目录和lib目录,编译c/c++的时候需要用到。
lua调用c/c++
static int average(lua_State* L)
{
int n = lua_gettop(L);
double sum=0;
int i = 0;
for(i=1;i<=n;i++)
{
if(!lua_isnumber(L,i))
{
lua_pushstring(L,"Incoorect argument to 'average'");
lua_error(L);
}
sum+=lua_tonumber(L,i);
}
lua_pushnumber(L,sum/n);
lua_pushnumber(L,sum);
return 2;
}
int _tmain(int argc, _TCHAR* argv[])
{
int nRet=0;
int nCount=0;
lua_State* L1=lua_open();
luaL_openlibs(L1);
lua_register(L1,"average",average);
nRet=luaL_dofile(L1,"E:/aoi_list/lua_call_c79/Debug/test.lua");
//lua_pcall(L1, 0, LUA_MULTRET, 0);
nCount = lua_gettop(L1);
cout<<"ncount is "<<nCount<<endl;
//lua_getglobal(L1,"avg");
cout<<"avg is:"<<lua_tointeger(L1,1)<<endl;
//lua_pop(L1,1);
//lua_getglobal(L1,"sum");
cout<<"sum is:"<<lua_tointeger(L1,2)<<endl;
lua_close(L1);
return 0;
}
avg,sum=average(10,20,30,40,50)
print("The average is",avg)
print("The sum is",sum)
c调用lua
#include <stdio.h>
#include <lua.hpp>
lua_State * L;
int luadd(int x,int y)
{
int sum=0;
lua_getglobal(L,"add");//压栈
lua_pushnumber(L,x);//实参入栈
lua_pushnumber(L,y);//实参入栈
lua_call(L,2,1);//进行调用,2个参数,x,y然后进行计算
sum=(int)lua_tonumber(L,-1);
lua_pop(L,1);
lua_getglobal(L,"z");
int z=lua_tonumber(L,-1);
lua_pop(L,1);
return sum;
}
int main()
{
int sum=0;
L=lua_open();
luaL_dofile(L,"E:/aoi_list/lua_call_c79/c_call_lua_79/add.lua");
sum=luadd(10,15);
printf("sum is %d",sum);
lua_close(L);
return 0;
}
function add(x,y)
return x+y+2
end
z=6
继续看