Lua adds / modifies global variables from C

I have a small Lua script:

function g () print( AUp); end 

From C Download the script, add a variable called AUp and let it run several 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)); } 

Print output is 0, always. If I put (i + 1) in, the output is always 1. I cannot change the value of AUp. The value remains unchanged, as in the very first call to lua_pushnumner and lua_setglobal.

What's wrong? The function should be called again and again, but the AUp value may change, so I have to update it before calling lua_call .

+5
source share
1 answer

I'm not sure, but you tried: 1. Determining the initial AUp value in a Lua script. 2. Clearing stack values ​​during cycle C.

EDIT: Forget these 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 well with Lua 5.1.5 Btw, according to manual - void lua_call (lua_State *L, int nargs, int nresults); (use lua_pcall() instead). It is not possible to compile your code with Lua 5.1.5 headers.

0
source

Source: https://habr.com/ru/post/1490699/


All Articles