Reputation: 41
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.
Upvotes: 0
Views: 11148
Reputation: 91
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.
Upvotes: 0
Reputation: 2407
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.
Upvotes: 1