lua-users home
lua-l archive

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


On Mon, Jul 18, 2011 at 02:40:50PM -0400, Dave Collins wrote:
> I know this is ultra basic. It's the ultra basic stuff that messes me up.

Hi Dave,

Could you please stop hijacking threads and changing their subjects?
Please compose a new mail rather than replying to another and
obliterating its content.

> 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.