lua_pcall(): attempt to call a n

2019-08-12  本文已影响0人  小灰_06e4

1、问题描述

  首先 调用luaL_loadbuffer(L,start_addr,len,0)载入lua代码,然后调用下面代码运行on_touch函数

     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在栈顶留下的信息会保留,影响后面函数调用

          lua_pop(L,-1); 

      }

出现错误 :lua_pcall(): attempt to call a nil value

2、原因分析

 函数luaL_loadbuffer只是loaded了lua代码,并未run lua代码,需要在 lua_getglobal函数之前调用 lua_pcall函数

3、解决办法

      lua_getglobal函数之前调用 lua_pcall函数

      代码改为:

      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在栈顶留下的信息会保留,影响后面函数调用

           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

上一篇 下一篇

猜你喜欢

热点阅读