简体   繁体   中英

Lua adding/changing global variables from C

I have a small Lua script:

function g ()
    print( AUp);
end

From CI load the script, add a variable with Name AUp and let it run a few hundred times.

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));
}

The Output of print is 0, always. If I put (i+1) in, the Output is always 1. I can't change the value of AUp. The value stays the same, like in the very first call to lua_pushnumner and lua_setglobal.

What is wrong? The function should be called again and again, but the value of AUp can Change, so I have to update it, before calling lua_call .

I'm not sure, but have You tried: 1. Defining AUp initial value in Lua script. 2. Cleaning stack values during C loop. ?

EDIT: Forget those two points :)

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));
            }
    }

and

function test_f()
    print(foo)
end

Works just fine with Lua 5.1.5 Btw, according manual - void lua_call (lua_State *L, int nargs, int nresults); (use lua_pcall() instead). Can't even compile Your code with Lua 5.1.5 headers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM