简体   繁体   中英

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)"

#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

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. Now, your problem might be something else, but try these steps at least and let us know how it went.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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