Lua从C添加/更改全局变量

Kar*_*lte 5 c variables lua

我有一个小的Lua脚本:

function g ()
    print( AUp);
end
Run Code Online (Sandbox Code Playgroud)

从CI加载脚本,添加一个名为AUp的变量,让它运行几百次.

for( i=0; i<2000; i++)
{
    num= i;
    lua_pushnumber( L, i);
    lua_setglobal( L, "AUp");

    lua_getglobal( L, "g");
    if (lua_call( L, 0, 0) != 0)
       printf( "%s", lua_tostring(L, -1));
}
Run Code Online (Sandbox Code Playgroud)

始终是打印输出为0.如果我输入(i + 1),则输出始终为1.我无法更改AUp的值.该值保持不变,就像第一次调用lua_pushnumner和lua_setglobal时一样.

怎么了?该函数应该一次又一次地调用,但是AUp的值可以改变,所以我必须在调用之前更新它lua_call.

Kam*_*olo 1

我不确定,但是您尝试过: 1. 在 Lua 脚本中定义 AUp 初始值。2. 在C 循环期间清理堆栈值。?

编辑:忘记这两点:)

for(i = 0; i<200; i++)
   {
            lua_pushnumber(l, i);
            lua_setglobal(l, "foo");

            lua_getglobal(l, "test_f");
            if (lua_pcall(l, 0, 0, 0) != 0)
            {
                    printf( "%s", lua_tostring(l, -1));
            }
    }
Run Code Online (Sandbox Code Playgroud)

function test_f()
    print(foo)
end
Run Code Online (Sandbox Code Playgroud)

根据手册,与 Lua 5.1.5 Btw 配合得很好- void lua_call (lua_State *L, int nargs, int nresults);lua_pcall()改为使用)。甚至无法使用 Lua 5.1.5 标头编译您的代码。

  • @KarlSchulte `lua_settop(L, 0);` 将清空堆栈。 (2认同)