Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

124
Visualizações
C calling Lua function in a for loop

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?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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).

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda