【cocos2d-x】控制台输入Lua指令方便调试改进版

之前也发过一篇关于从控制台输入Lua指令的文章,虽然简单,但其实是有多线程方面的问题的,可能会造成程序宕掉,后来稍微改造了下,方法如下:

1 首先在行首加入lua的引用,如下 [cpp] #include “main.h” #include “AppDelegate.h” #include “cocos2d.h” #include <assert.h> #include <windows.h> #include <sys/stat.h> #include “CCLuaEngine.h” [/cpp] 2 在main函数前面插入以下代码 [cpp] #ifdef USE_WIN32_CONSOLE BOOL g_bAppRun = FALSE; char g_szBuffer[1024]; char g_szBuffer_copy[1024]; DWORD WINAPI ThreadReadConsole(LPVOID lpParam) { HANDLE hConsole = GetStdHandle(STD_INPUT_HANDLE); while(g_bAppRun) { DWORD dwNum = 0; ReadConsoleA(hConsole, g_szBuffer, 1023, &dwNum, NULL); if (dwNum) { g_szBuffer[dwNum] = ‘\0’; memcpy(g_szBuffer_copy, g_szBuffer, dwNum + 1); } } return 0; } int FetchConsoleCmd(lua_State* L) { if (‘\0’ == g_szBuffer_copy[0]) { return 0; } lua_pushstring(L, g_szBuffer_copy); g_szBuffer_copy[0] = ‘\0’; return 1; } #endif [/cpp] 3 在main函数里修改如下 [cpp] #ifdef USE_WIN32_CONSOLE AllocConsole(); freopen(“CONIN$”, “r”, stdin); freopen(“CONOUT$”, “w”, stdout); freopen(“CONOUT$”, “w”, stderr); g_bAppRun = TRUE; CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadReadConsole,NULL,0,NULL); #endif // create the application instance AppDelegate app; lua_State* L = LuaEngine::getInstance()->getLuaStack()->getLuaState(); lua_register(L, “FetchConsoleCmd”, FetchConsoleCmd); int ret = Application::getInstance()->run(); #ifdef USE_WIN32_CONSOLE FreeConsole(); g_bAppRun = FALSE; #endif [/cpp] 4 在你的Lua的主循环循环代码里加入如下代码 [cpp] local function MainLoop(delta) if FetchConsoleCmd then local string = FetchConsoleCmd() if string then local cmd = loadstring(string) if cmd then xpcall(cmd, __G__TRACKBACK__) end end end …… end [/cpp] OK,现在放心大胆的往控制台里输入你的指令吧!!!