关闭

Lua与c/c++交互

314人阅读 评论(0) 收藏 举报
分类:

先安装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


继续看

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:4436次
    • 积分:85
    • 等级:
    • 排名:千里之外
    • 原创:1篇
    • 转载:11篇
    • 译文:0篇
    • 评论:0条
    文章分类