lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> myconfig = { }
> config_function = assert(loadfile "config.txt") 
> setfenv(config_function, myconfig)

I'm afraid your solution is over my head. I read up on loadfile, and all it does is take my filename. So this is what I've interpreted:

config ={}
function load_config()
	local config_file_name = gre.SCRIPT_ROOT .. "/../runtime_config.txt"
	local config_function = assert(loadfile(config_file_name))
	setfenv(config_function, config)
	dump_table(config)
end


When config is dumped to screen, it is nil.

Dave




> I want to load a config file into a table. I already know the config file's name ("config.txt"). Do not know the parameters that might be in the file.
> 
> 
> I've tried a few samples but they're either too simple or too complex for my purposes and I can't really decipher them.
> This has fixed, known param names:
> http://stackoverflow.com/questions/1891473/how-to-load-text-file-into-
> sort-of-table-like-variable-in-lua
> which I do not have.
> 
> So, simply:
> 
> network = false
> flyer_id = 7009
> etc.
> 
> gives me a table object.

Use setfenv().  You can use loadfile() to load your configuration into a function, and then use setfenv() to control what is used for global storage.


rjek@octopus:~$ cat > config.txt <<EOF
> network = false
> flyer_id = 7009
> EOF
rjek@octopus:~$ lua
Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> myconfig = { }
> config_function = assert(loadfile "config.txt") 
> setfenv(config_function, myconfig)
> config_function()
> =myconfig.network
false
> =myconfig.flyer_id
7009
> =myconfig.spatula
nil

You would probably want to check the return values of loadfile() rather than just asserting (to check for syntax errors) and use pcall() to run
config_function() (to check for runtime errors.)

You can also change your configuration file syntax and use other approaches, such as using function calls that take parameters and set up the configuration, or use metamethods for more expressiveness.

B.