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;
}