美文网首页
lua_pcall(): attempt to call a n

lua_pcall(): attempt to call a n

作者: 小灰_06e4 | 来源:发表于2019-08-12 11:55 被阅读0次

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

相关文章

网友评论

      本文标题:lua_pcall(): attempt to call a n

      本文链接:https://www.haomeiwen.com/subject/rbwyjctx.html