c++调用lua

extern "C"
{
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
}


void load(char *filename , int *width , int *height )
{
lua_State *L = lua_open();


luaopen_base(L);


luaL_openlibs(L);


//luaopen_table(L);


//luaopen_io(L);


//luaopen_string(L);


//luaopen_math(L);


if(luaL_loadfile(L ,filename) || lua_pcall(L , 0 , 0 , 0) )
//error(L, "cannot run configuration file: %s",lua_tostring(L, -1));
return ;






lua_getglobal(L,"width");
lua_getglobal(L,"height");


if( !lua_isnumber(L,-2))
//error(L,"Width should be a number\n");
return ;


if(!lua_isnumber(L ,-1))
//error(L,"height should be a number \n");
return ;


*width   = (int)lua_tonumber(L,-2);
*height  = (int)lua_tonumber(L,-1);


lua_close(L);


}


void main()
{
int a = 1;
int *width = 0 ;
int *height = &a ;
load("test.lua" , width , height);

}




test.lua 配置

width = 100 

height = 100




///实例二

extern "C"
{
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
}


lua_State *L;


int luaAdd( int x , int y )
{
int sum;
lua_getglobal( L , "add" );
lua_pushnumber(L , x );
lua_pushnumber(L ,y );
lua_call(L ,2 , 1);
sum = (int)lua_tonumber(L ,-1);
lua_pop(L ,-1);
return sum;
}


int main(int argc , char* argv[] )
{
int sum = 0;
L = lua_open();
luaopen_base(L);
luaL_openlibs(L);
luaL_loadfile(L,"add.lua");
lua_pcall(L,0,LUA_MULTRET , 0);
sum = luaAdd(10,15);
printf("The sum is %d\n" ,sum);
lua_close(L);
return 0;
}



add.lua配置   必须放置与工程目录 .cpp文件同一个文件夹里面

2 function add(x, y)
3     return x + y
4 end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值