lua c++ (一)

lua  脚本

function add(a, b)
	return a+b;
end


为了调用一个LUA函数,我们首先要把函数压栈。
这个函数的结果由参数决定,所以,我们要调用函数将需要
lua_call(),调用这个函数之后,返回的结果将在堆栈中存在。

整个步骤:
1.用lua_getglobal()把add函数放入堆栈
2.用lua_pushnumber()把第一个参数压入堆栈
3.用lua_pushnumber()把第二个参数压入堆栈
4.用lua_call()调用函数。
5,现在用lua_tonumber从堆栈头取出结果
6,最后用lua_pop从堆栈中移除结果值。

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

#include <iostream>
#include <string>
using namespace std;

lua_State *pL;

int luaAdd(int x, int y)
{
	int sum;
	/*--首先将函数名压入栈*/
	lua_getglobal(pL, "add");
	
	lua_pushnumber(pL, x);
	lua_pushnumber(pL, y);
	
	/*--call the function with 2 args ,return 1 result*/
	lua_call(pL, 2, 1);
	
	/*--get the result*/
	sum = (int)lua_tonumber(pL, -1);
	lua_pop(pL, 1);
	
	return num;

}

int main()
{
	pL = lua_open();
	luaL_openlibs(pL);
	
	luaL_dofile(pL, "1029.lua");
	int sum = luaAdd(10, 19);
	
	cout<<"the sum is "<<sum<<endl;
	lua_close(pL);
	return 0;
	

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值