lua-users home
lua-l archive

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


> -- 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