Reputation: 27
I would like to load a config.lua file containing global variables so that I can wrap and then access those variables into a local table.
config.lua looks like this:
prop01=value01
prop02=value02
script.lua would look like this
-- fragment starts --
local config = {
-- something goes here
}
-- fragment end --
print (config.prop01) -- should print "value01"
print (config.prop02) -- should print "value02"
How can I change the "fragment" to get expected printout?
Upvotes: 1
Views: 552
Reputation: 2358
Swap the environment when loading the config file.
In lua 5.3 it is done using functions load
or loadfile
documented here:
local config={}
local config_init_fun = loadfile('config.lua',"configuration file",config)
config_init_fun()
In lua 5.1 you will need to use setfenv
function:
local config={}
local config_init_fun = loadfile('config.lua',"configuration file")
config_init_fun = setfenv (config_init_fun, config)
config_init_fun()
The assignment of setfenv result might be unnecessary but I don't have lua5.1 at hand to verify that.
All that assuming that config.lua is a valid script that is setting some global variables.
Upvotes: 1