lua-users home
lua-l archive

Re: how to read lua table present in file

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


On 10/16/2017 05:23 AM, prashantkumar dhotre wrote:
> hi
> i am new to lua. i have a query related to table reading from file.
> i have a config file in lua table format:
> example:
> return {
> ["param1"] = {
> ["attribute"] = {
> ["myparam"] = 1,
> }
> },
> ["param2"] = 1
> }
>
> could you please let me know how do i read this file and access my config file
> parameters ?
> Thanks
Suppose your config file is named "config.lua" and located in same
directory as .lua file from where you calling it. Then you may load
config as
 local config = dofile('config.lua')
or
 local config = require('config')
(Way via require() caches result, so several require('config')
will yield to one reading from file.)
Now variable "config" is just ordinary Lua table.
You can get it's values like
 local myparam
 if
 config.param1 and
 config.param1.attribute
 then
 myparam = config.param1.attribute.myparam
 end
 print('myparam', myparam)
(Here I'm showing "safe" way. You may drop "if" check if you sure
that "param1.attribute" is always present.)
-- Martin

AltStyle によって変換されたページ (->オリジナル) /