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.

2
  • Do you get an error when compiling the file? For example, does Lua actually find add.lua correctly? Commented Aug 18, 2012 at 11:33
  • 2
    I got the answer,you cannot image,i put the add.lua in an incorrect directory, i put it in a directory where the cpp file is, when i put it in the project directory ,then it works. thankyou @lhf and Nicol Bolas. Commented Aug 18, 2012 at 12:27

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.