1愉耙、問(wèn)題描述
? 首先 調(diào)用luaL_loadbuffer(L,start_addr,len,0)載入lua代碼,然后調(diào)用下面代碼運(yùn)行on_touch函數(shù)
? ?? lua_getglobal(L,"on_touch");
? ? ? lua_pushinteger(L,ntouch);
??????error = lua_pcall(L,1,0,0);
????? if(error)
????? {
??????????printf("\n%s\n",lua_tostring(L,-1));
????????//此句不能少猜谚,否則lua_tostring在棧頂留下的信息會(huì)保留,影響后面函數(shù)調(diào)用
??????????lua_pop(L,-1);?
????? }
出現(xiàn)錯(cuò)誤 :lua_pcall(): attempt to call a nil value
2魏铅、原因分析
?函數(shù)luaL_loadbuffer只是loaded了lua代碼,并未run lua代碼斜姥,需要在 lua_getglobal函數(shù)之前調(diào)用 lua_pcall函數(shù)
3、解決辦法
? ? ? lua_getglobal函數(shù)之前調(diào)用 lua_pcall函數(shù)
? ? ? 代碼改為:
? ? ? luaL_loadbuffer(L,start_addr,len,0)铸敏;
? ? ? lua_pcall(L,0,0,0);? //新添加的代碼
? ? ?? lua_getglobal(L,"on_touch");
? ? ?? lua_pushinteger(L,ntouch);
? ? ?? error = lua_pcall(L,1,0,0);
? ? ?? if(error)
? ? ?? {
? ? ? ? ?? printf("\n%s\n",lua_tostring(L,-1));
? ? ? ?? //此句不能少悟泵,否則lua_tostring在棧頂留下的信息會(huì)保留,影響后面函數(shù)調(diào)用
? ? ? ? ?? lua_pop(L,-1);?
? ? ? ? }
4桩撮、參考資料
????https://stackoverflow.com/questions/20380232/lua-5-2-issue-attempt-to-call-a-nil-value-from-lua-pcall
????https://stackoverflow.com/questions/20380232/lua-5-2-issue-attempt-to-call-a-nil-value-from-lua-pcall
????http://www.troubleshooters.com/codecorn/lua/lua_c_calls_lua.htm