//main.cpp
#include <iostream>
extern "C"
{
#include "lualib/lua.h"
#include "lualib/lualib.h"
#include "lualib/lauxlib.h"
}
using namespace std;
int main()
{
lua_State* L = luaL_newstate() ;
luaopen_base(L) ;// 不知道为什么这里使用luaL_openlibs(L)会报错
luaL_dofile(L, "script/test.lua") ;
lua_getglobal(L, "add") ;
lua_pushnumber(L, 1) ;
lua_pushnumber(L, 2) ;
lua_pcall(L, 2, 1, 0) ;
int sum = (int)lua_tonumber(L, -1) ;
lua_pop(L, -1) ;
lua_close(L) ;
cout << "1 + 2 = " << sum << endl;
return 0 ;
}
function add(x, y)
return x + y
end
编译命令:
g++ main.cpp -L./lualib -llua
实际上就C++通过Lua脚本调用自己的函数。
cocos2dx中那些个Lua接口,调用的都是C++中定义的函数。
// main.cpp
#include <iostream>
extern "C"
{
#include "lualib/lua.h"
#include "lualib/lualib.h"
#include "lualib/lauxlib.h"
}
using namespace std;
lua_State* L ;
static int average(lua_State *L)
{
// num of args
int n = lua_gettop(L) ;
double sum = 0 ;
int i = 0 ;
for ( i = 1; i <= n; ++i)
{
sum += lua_tonumber(L, i) ;
}
// push the average
lua_pushnumber(L, sum / n) ;
// push the sum
lua_pushnumber(L, sum) ;
return 2;
}
int main()
{
L = luaL_newstate() ;
luaopen_base(L) ;
// register function
lua_register(L, "average", average) ;
luaL_dofile(L, "test.lua") ;
lua_close(L) ;
return 0 ;
}
avg, sum = average(1, 2, 3, 4, 5)
print ("The average is ", avg)
print ("The sum is ", sum)
先就到这里了。假设有错误还请路过的大神指点一二。