0

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.

4

2 回答 2

1

你知道吗,我遇到了同样的问题,并通过意识到当从代码块运行某些东西时,它与磁盘上可执行文件所在的位置没有相同的工作目录来解决它。从 cmd 运行以确保我有正确的工作目录,确保我的 c++ 程序确实可以找到 lua 文件,并在ideone验证我的 lua 代码是否有错误时,我能够成功运行。现在,您的问题可能是其他问题,但至少尝试这些步骤并让我们知道它是如何进行的。

于 2014-05-25T07:44:21.687 回答
0

Make sure your filename is add.lua,not lua.add.Because I once mistaken the name and the error appered was same with yours.After I changed it correctly,it worked.And don't forget to put it in the the same directory with your executable file.

于 2017-07-21T09:23:52.310 回答