[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: RE: load config file into table
- From: Dave Collins <Dave.Collins@...>
- Date: Mon, 18 Jul 2011 15:45:52 -0400
Got it.
config ={}
function load_config()
local config_file_name = gre.SCRIPT_ROOT .. "/../runtime_config.txt"
local f = assert(io.open(config_file_name, "r"))
for line in f:lines() do
table.insert(config, line)
end
end
Dave Collins
Front-End Engineer
Mercatus Technologies Inc.
60 Adelaide Street East, Suite 700
Toronto ON M5C 3E4
T 416 603 3406 x 298
F 416 603 1790
dave.collins@mercatustechnologies.com
www.mercatustechnologies.com
-----Original Message-----
From: lua-l-bounces@lists.lua.org [mailto:lua-l-bounces@lists.lua.org] On Behalf Of Dave Collins
Sent: Monday, July 18, 2011 3:23 PM
To: Lua mailing list
Subject: RE: load config file into table
> 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.