Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing global variables between different Lua states through require

Tags:

c++

lua

I'm trying to find a way to share global variables of a specific Lua script(test.lua in the example) between different Lua states.

Here's my simple example code:

In test.lua

num = 2

In main.cpp

#include <iostream>
#include <lua.hpp>
int main() 
{    
    lua_State *L1 = luaL_newstate(); //script A
    luaL_openlibs(L1);
    lua_settop(L1, 0);
    luaL_dostring(L1, "require('test') num = 5");

    lua_State *L2 = luaL_newstate(); //script B
    luaL_openlibs(L2);
    lua_settop(L2, 0);
    luaL_dostring(L2, "require('test') print(num)");

    lua_close(L1);
    lua_close(L2);
}

I expect to get 5 but I get 2.

Is not possible to share global variables between different lua_State* through require?

ADDED :

If it's not possible, would it be a good idea to open test.lua using luaL_loadfile and then create getter/setter methods in C++ to share variable num between script A and B?

For example like this,

Script A:

script = my.Script("test")
script:setVar("num", 5)

Script B:

script = my.Script("test")
print(script:getVar("num"))

I wonder what you think about this design as an alternative to require.

like image 298
Zack Lee Avatar asked Apr 25 '26 20:04

Zack Lee


1 Answers

Two distinct lua_States are completely and totally independent. One cannot directly affect anything that happens in another. You can expose some C code to one that allows it to modify the other, or they could both access some external resource (a file, for example) that allows them to share data.

But outside of things like this, no, they cannot interact.

The preferred method for this is to not make them separate lua_States.

like image 169
Nicol Bolas Avatar answered Apr 28 '26 08:04

Nicol Bolas