C calls the Lua function in a for loop

My Lua file named "add4c.lua", Lua code:

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 version of Lua is 5.1.4, and my c-code was compiled by Visual Studio 2013. When I run this code, it causes an error, it just stops the code, but there is no message, and if I change the loop sentence, for example, "i <= 10" It works great, how to fix it?

+4
source share
1 answer

lua_call(L, 3, 1)consumes 3 stack values ​​and leaves 1 when done. Thus, after lua_call(L, 3, 1)there is only one value in the stack, therefore it lua_pop(L, 4)pushes too many values ​​and goes beyond the limits of the internal stack, therefore, a failure. Use instead lua_pop(L, 1).

Lua LUA_USE_APICHECK, lua_pop(L, 4).

+4

All Articles