[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Depth indexing of nil
- From: Roberto Ierusalimschy <roberto@...>
- Date: Thu, 9 Jul 2015 13:16:24 -0300
> -- somewhere, e.g. module
> local nothing = setmetatable({}, {
> __index = function(nothing)
> return nothing
> end,
> __call = function()
> return nil
> end,
> })
>
> function maybe(tab)
> return setmetatable({}, {
> __index = function(_, key)
> if tab[key] then
> return maybe(tab[key])
> else
> return nothing
> end
> end,
> __call = function()
> return tab
> end,
> })
> end
>
> -- then
>
> a = { b = { c = 123 } }
>
> print( maybe(a).b.c() ) -- 123
> print( maybe(a).x.c() ) -- nil
>
> --
>
> I'm not 100% happy with it, but I think it'd cover most my use cases.
When all fields are present, that code will create two new tables plus
two new closures at each dot: for instance, maybe(a).b.c() creates four
new objects. That sounds quite expensive.
-- Roberto