原文地址:http://blog.csdn.net/dingkun520wy/article/details/49839701函數
1.引入頭文件測試
#include "cocos2d.h" #include "CCLuaEngine.h" USING_NS_CC; using namespace std; extern "C"{ #include "lua.h" #include "lualib.h" #include "lauxlib.h" }
2導入Lua文件ui
若是是cocos2dx的Lua工程只須要在main.lua裏面引用就能夠了lua
3.Lua文件編寫spa
--Lua變量 strTemp = "樂逍遙" --Lua的table tableTemp = {name = "樂逍遙Jun", uuid = "001"} --沒有參數的函數 function test() return 100 end --有參數的函數 function testadd(a,b,str) local c = a+b return c, str end
4.C++中的調用.net
首先是找到AppDelegate.cpp中的code
#if (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT >0)blog
將 CC_CODE_IDE_DEBUG_SUPPORT的值改成0 get
若是是沒有參數只有一個int返回值的Lua函數只須要調用cocos2dx封裝好的executeGlobalFunction函數就行string
auto engine = LuaEngine::getInstance(); engine->executeGlobalFunction("test");
若是是比較負責的函數
LuaStack * L =LuaEngine::getInstance()->getLuaStack(); lua_State* tolua_s = L->getLuaState(); //--------有參數和返回值的Lua函數的調用--------- lua_getglobal(tolua_s, "testadd"); // 獲取函數,壓入棧中 lua_pushnumber(tolua_s, 10); // 壓入第一個參數 lua_pushnumber(tolua_s, 20); // 壓入第二個參數 lua_pushstring(tolua_s, "測試"); // 壓入第三個參數 int iRet= lua_pcall(tolua_s, 3, 2, 0);// 調用函數,調用完成之後,會將返回值壓入棧中,2表示參數個數,1表示返回結果個數。 if (iRet) // 調用出錯 { const char *pErrorMsg = lua_tostring(tolua_s, -1); CCLOG("錯誤-------%s",pErrorMsg); return ; } int fValue = lua_tonumber(tolua_s, -2); //獲取第一個返回值 string str = lua_tostring(tolua_s, -1); //獲取第二個返回值 CCLOG("有參數和返回值的Lua函數的調用---%d---,%s",fValue,str.c_str()); //--------------讀取Lua的變量------------ lua_getglobal(tolua_s, "strTemp"); string strTemp = lua_tostring(tolua_s, -1); CCLOG("讀取Lua的變量---%s",strTemp.c_str()); //-------------讀取Lua的table----------- lua_getglobal(tolua_s,"tableTemp"); lua_getfield(tolua_s,-1,"name"); string strName = lua_tostring(tolua_s,-1); CCLOG("讀取Lua的table--%s",strName.c_str());
5.注意事項
1.若是你是cpp調用lua函數,那麼你的這個lua函數不能是local的