Reputation: 477
My Lua file named "add4c.lua", Lua code like this:
function lua_sum(x,y,z)
return x+y+z
end
My C file code is like :
#include "D:/luac/include/lua.h"
#include "D:/luac/include/lualib.h"
#include "D:/luac/include/lauxlib.h"
#include <stdlib.h>
#pragma comment(lib,"D:/luac/lib/lua51.lib")
int main(void)
{
lua_State *L = luaL_newstate();
luaopen_base(L);
luaL_openlibs(L);
int error = luaL_dofile(L, "add4c.lua");
double r;
for (int i = 0; i <= 200; i++){
lua_getglobal(L, "lua_sum");
lua_pushnumber(L, i+1);
lua_pushnumber(L, i+2);
lua_pushnumber(L, i+3);
lua_call(L, 3, 1);
r = lua_tonumber(L, -1);
printf("%d\n", i);
lua_pop(L, 4);
}
lua_close(L);
return 0;
}
My Lua version is 5.1.4,and my c code is compiled by Visual Studio 2013.When running this code,It causes an error simply stop the code,but no message,and if I change the loop clause like "i<=10",it works fine,how to fix this?
Upvotes: 4
Views: 918
Reputation: 72312
lua_call(L, 3, 1)
consumes 3 stack values and leaves 1 when it is done. So, after lua_call(L, 3, 1)
there is only one value on the stack and so lua_pop(L, 4)
is popping too many values and going outside the internal stack, hence the crash. Use lua_pop(L, 1)
instead.
If you rebuild Lua with LUA_USE_APICHECK
defined, then you'll get an error message from an internal assert the first time you call lua_pop(L, 4)
.
Upvotes: 4