交互主要是通过栈进行交互,一个lua_State表示一个栈,使用完记得清空栈,栈从下到上分别是1,2,3,4.....,从上到下分别是-1,-2,-3....
头文件
#ifndef _SCRIPT_MANAGER_H #define _SCRIPT_MANAGER_H #include "Common.h" extern "C" { #include "..\\libs\\lua\\lua.h" #include "..\\libs\\lua\\lualib.h" #include "..\\libs\\lua\\lauxlib.h" }; class ScriptManager { DECLARE_SINGLETON(ScriptManager); public: ScriptManager(); ~ScriptManager(); static int average(lua_State * m_State); private: lua_State * m_State; }; #endif
源文件
#include "ScriptManager.h" DEFINE_SINGLETON(ScriptManager,_scriptManager); int ScriptManager::average(lua_State * m_State) { //每个函数都有自己的局部私有栈,每当Lua调用一个C函数时,第一个参数总是这个局部栈的索引1, //即使这个C函数调用了Lua代码,Lua代码又调用了相同的C函数,这些C函数只看到自己的私有栈,他们的第一个 //参数都是索引1,完成后会自动清栈 CCLog("lua call average"); int size=lua_gettop(m_State); CCLog("size fun:%d",size); int i=lua_tonumber(m_State,1); int j=lua_tonumber(m_State,2); lua_pushnumber(m_State,i); lua_pushnumber(m_State,j); return 2;//结果的数量(一般压人几个就是几) } ScriptManager::ScriptManager()//需要注意清空栈 { //初始化Lua库 m_State=lua_open(); luaL_openlibs(m_State); const luaL_reg libs[]={ {"average",&ScriptManager::average}, {NULL,NULL} }; luaL_register(m_State,"go",libs);//将Lua要调用的函数注册进来 lua_pop(m_State,1);//弹出栈的n个元素 luaL_dofile(m_State,"simple.lua"); //s_100这个table此时位于栈低,从下到上是1,2,3,4递增,从上到下是-1,-2,-3 lua_getglobal(m_State,"s_s"); lua_getfield(m_State,1,"name"); const char * name=lua_tostring(m_State,-1); CCLog("name:%s",name); lua_getfield(m_State,1,"loop"); bool loop=lua_toboolean(m_State,-1); CCLog("loop:%d",loop); lua_getfield(m_State,1,"time"); int time=lua_tonumber(m_State,-1); CCLog("time:%d",time); lua_getfield(m_State,1,"script"); if(!lua_isfunction(m_State,-1)) { CCLog("not function"); } lua_pushnumber(m_State,10); lua_pushnumber(m_State,20); lua_pcall(m_State,2,1,0);//调用该函数后,会自动清空函数的栈 int max=lua_tonumber(m_State,-1); CCLog("max:%d",max); int size=lua_gettop(m_State); CCLog("%d",size); lua_getglobal(m_State,"width"); int width=lua_tonumber(m_State,-1); CCLog("width:%d",width); size=lua_gettop(m_State); CCLog("size1:%d",size); lua_newtable(m_State);//创建一个table lua_pushnumber(m_State,1);//向栈顶压入一个元素 lua_setfield(m_State,-2,"test");//设置到table中去,这时候栈顶的number弹出栈 size=lua_gettop(m_State); CCLog("size3:%d",size); } ScriptManager::~ScriptManager() { lua_close(m_State); }
simple.lua
s_s= { name="gameone"; loop=false; time=20; script=function(x,y) i,j=go.average(x,y); if x>=y then return x+i; else return y+j; end end } width=10; height=20;