title: Sharing global variables between different Lua states through require
body: <p>I'm trying to find a way to share global variables of a specific Lua script(<code>test.lua</code> in the example) between different Lua states.</p>
  
  <p>Here's my simple example code:</p>
  
  <p>In <code>test.lua</code></p>
  
  <pre><code>num = 2
  </code></pre>
  
  <p>In <code>main.cpp</code> </p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;lua.hpp&gt;
  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);
  }
  </code></pre>
  
  <p>I expect to get <code>5</code> but I get <code>2</code>.</p>
  
  <p>Is not possible to share global variables between different <code>lua_State*</code> through <code>require</code>?</p>
  
  <p><strong>ADDED :</strong></p>
  
  <p>If it's not possible, would it be a good idea to open <code>test.lua</code> using <code>luaL_loadfile</code> and then create getter/setter methods in C++ to share variable <code>num</code> between script <code>A</code> and <code>B</code>?</p>
  
  <p>For example like this,</p>
  
  <p>Script A: </p>
  
  <pre><code>script = my.Script("test")
  script:setVar("num", 5)
  </code></pre>
  
  <p>Script B:</p>
  
  <pre><code>script = my.Script("test")
  print(script:getVar("num"))
  </code></pre>
  
  <p>I wonder what you think about this design as an alternative to <code>require</code>.</p>