Say I have two Lua files which I'll be using from the standard Lua C API, that share a common library:
common.lua
function printHello(name)
print("Hello from " .. name)
end
file1.lua
require "common"
local scriptName = "file1"
function doSomething()
printHello(scriptName)
end
file2.lua
require "common"
local scriptName = "file2"
function doSomething()
printHello(scriptName)
end
Now say I want to have both file*.lua files share the same lua_State
. Without changing any of the Lua code, how can I load the files in way such that I can call a specific doSomething()
?
Is there a way I can move "everything" from the loaded files (functions, variables, tables) it into a global table within the lua_State
using the script-name (or whatever) as the key? Also, is there a way I can do this such that file1.lua and file2.lua can share the "in memory" version of common.lua?
I am using Lua 5.1.
Thanks!
Here's how you do it in pure Lua 5.1:
What's going on is you're changing the environment that each file's chunk runs in, so instead of putting their
doSomething
functions in the global environment and thus stomping each other, they go in their own local environment (which uses a metatable so they can use things that are in the global environment likerequire
andprint
). And as requested,common.lua
only has to run once, as you'll see if you put something likeprintHello('common')
at the end of it.If you want to do this from C, all of the functionality I used can be straightforwardly converted to the C API, like this: