My Code:
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_settop(L, 0);
//Script A
luaL_dostring(L, "A = {} A.num = 3");
//Script B
luaL_dostring(L, "B = {} function B.update() return A.num * 2 end");
//Script C
luaL_dostring(L, "print(B.update())");
lua_close(L);
The Result: 6
However if I make the table A and B local like the following:
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_settop(L, 0);
//Script A
luaL_dostring(L, "local A = {} A.num = 3");
//Script B
luaL_dostring(L, "local B = {} function B.update() return A.num * 2 end");
//Script C
luaL_dostring(L, "print(B.update())");
lua_close(L);
It doesn't output anything.
How to make the second code work and what is more recommended design between the two?
ADDITIONAL QUESTION: Is putting all functions and variables inside a uniquely named table per .lua file a common technique in Lua to avoid name collision between each files?
dostringintroduces separate chunk.luaL_dostring(L, "print(B.update())");in second example will fail with something likefailed to index nil global "B"