简体   繁体   中英

Change global vars in Lua from C 'globally'

Can you change the value of a global field in an entire .lua-file if you re-set this global field from C ?

this could be the lua-file:

GlobalVar   = 123      

Table1 = {ID = 1,   Val = GlobalVar}      -- Val = 123

Now if I call via Lua's C-API...

luaL_loadfile(lua, "lua-file" ...

lua_pushstring(lua, "321");
lua_setglobal(lua, "GlobalVar");

this only changes "GlobalVar" to 321 but not "Val" from "Table1".

It seems like the initial value of GlobalVar is copied to Table1 when the .lua-file is loaded for the first time.

Is there a way to update the entire lua-file?

As @Youka has described in a comment, you can't do this because the value is copied at the time you initialize Table1 . If what you're doing is setting the globals, then running the lua code once, you can conditionally initialize the globals in the Lua file:

if GlobalVar == nil then GlobalVar = 123 end

Table1 = {ID = 1,   Val = GlobalVar}      -- Val = 123

This gives you a chance to establish the global first from C with lua_setglobal , or accept the default.

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