lua-users home
lua-l archive

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


On Mon, Aug 23, 2010 at 1:55 PM, Wesley Smith <wesley.hoke@gmail.com> wrote:
> Is this what you're trying to do?
>
> local meta
> meta = {
>
>        __index = function(t, k)
>                print("__index", t, k)
>                if(not rawget(t, k)) then
>                        rawset(t, k, setmetatable({}, meta))
>                end
>                return t[k]
>        end,
>
>        __newindex = function(t, k, v)
>                print("__newindex", t, k, v)
>                rawset(t, k, v)
>        end
> }
>
>
> -- config.network.server.url
> local config = setmetatable({}, meta)
> config.network.server.url = "http://www.lua.org";
>

The original problem is to quickly check whether config.network.server.url
currently exists, without throwing an error if config.network is nil or
config.network.server is nil. Your solution wouldn't help with that:

  local config = setmetatable({}, meta)
  -- I want to know whether config.foo.bar.baz has been set to a value...
  if config.foo.bar.baz then
    -- ...but this code will *always* be run, because if it *wasn't*
    -- already set, it will have been created dynamically by the metatable.
  end

-Duncan