lua-users home
lua-l archive

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




Ok, well let’s take a trivial and contrived example of a UI configuration.  The configuration might look something like this:

UI = {
  mainwindow = {
    size = {
      width = 100,
      height = 200
    }
  }
}

Now, my code wants to use this information very simply:

local width = config.UI.mainwindow.size.width

But before I can do that, as a minimum I need to verify the structure and format of the config before I can safely use it.  Very naively, I might do something like this:

local width
if type(UI) == ’table’ then
  if type(UI.mainwindow) == ’table’ then
    if type(UI.mainwindow.size) == ’table’ then
      — now can access safely
      width = UI.mainwindow.size.width
    end
  end
end


 I can't find the thread now but I think Luiz suggested a technique like:

debug.setmetatable(nil,{__index = function(t,k) return nil end})
now you can just do
t = {}
t.x   -- nil
t.x.a -- nil
t.x.a.b -- nil

So now you can just load the config and do:
width = UI.mainwindow.size.width or 23 (or whatever is the default)