简体   繁体   English

Lua errorPANIC:调用Lua API时出现不受保护的错误(尝试调用nil值)

[英]Lua errorPANIC: unprotected error in call to Lua API (attempt to call a nil value)

this is the code, when execute get the error:"PANIC: unprotected error in call to Lua API (attempt to call a nil value)" 这是代码,执行时得到错误:“ PANIC:调用Lua API时出现非保护错误(试图调用nil值)”

#include <stdio.h>
extern "C"{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
};

lua_State *L;
int luaAdd(int x, int y)
{
int sum;
lua_getglobal(L, "add");
lua_pushnumber(L, x);
lua_pushnumber(L, y);
lua_call(L, 2, 1);
sum = (int)lua_tonumber(L, -1);
lua_pop(L, 1);
return sum;
}


int main(int argc, char *argv[])
{
  int sum = 0;
  L = lua_open();
  luaL_openlibs(L);
  luaL_dofile(L, "add.lua");
  sum = luaAdd(10, 15);
  printf("The sum is %d\n", sum);
  lua_close(L);

  return 0;
}

add.lua add.lua

function add(x, y) do
  return x + y
end
end

can you tell me ,where am i wrong. 你能告诉我,我哪里错了。 thanks in advance. 提前致谢。

You know what, I had the same problem and solved it by realizing that when running something from codeblocks, it didn't have the same working directory as the place on disk where the executable is . 您知道吗,我遇到了同样的问题,并通过意识到在从代码块运行某些内容时, 它没有与可执行文件所在的磁盘上相同的工作目录来解决了该问题 When running from cmd to make sure I had the right working directory, making sure that my c++ program really could find the lua file, and validating my lua code for errors at ideone , I was able to run successfully. 从cmd运行以确保我具有正确的工作目录时, 确保我的c ++程序确实可以找到lua文件,并ideone处验证lua代码中的错误,我才能成功运行。 Now, your problem might be something else, but try these steps at least and let us know how it went. 现在,您的问题可能是其他问题,但是至少尝试这些步骤,并让我们知道它的运行方式。

确保您的文件名是add.lua ,而不是lua.add 。因为我曾经误输入名称,并且所输入的错误与您的相同。正确更改后,它就可以了。不要忘记将其放在相同的位置可执行文件的目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM