lua-users home
lua-l archive

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


On Jul 14, 2012 12:26 AM, <meino.cramer@gmx.de> wrote:
>
> Hi,
>
> currently I am writing a standalone lua application. This application
> needs a config file, which I want to implement as an hash
> table...something like this:
>
> profile={ SoC_a=( baudrate=115200,port="/dev/ttyS1"}}
>
> and put into an additional file in $HOME or equivalent.
>
> But how can I load it back into my application?
>
> The explanation of loadfile() says, that the code will be compiled
> and stored "for later execution". But my config file does not
> have anything to call or execute.
> How it becomes accessible from inside my application?
>
> What is the best lua-ish way to accomplish the handling of
> config files, which are valid lua code?
>
> Thank you very much in advance for any help!
> Have a nice weekend and less rain ;)
> Best regards,
> mcc
>
>

loadfile() returns a function whose body is the file's contents. So to load a config file which is Lua code, you'd do something like:
local cfg = assert(loadfile('config.lua'))
config = cfg()

assuming your config file looks like:
return { address = 'example.com', port = 80 }

The result is the same as writing:
local cfg = function()
  return { address = 'example.com', port = 80 }
end
config = cfg()

From there, you can extrapolate how to use environments and sandboxing to make your config file a little more user-friendly and try to protect against malicious config files, if that's necessary for your application. e.g. if you create a 'config' table and make it the environment for cfg, then your config file can look like:
address = 'example.com'
port = 80
which users might find a little easier to work with.