lua-users home
lua-l archive

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


On 09/07/15 15:35, Roberto Ierusalimschy wrote:
> My prefered technique is this one:
> 
>   -- put this somewhere in your code; it can be global or local:
>   E = {}
> 
>   if ((((a or E).b or E).c or E).d or E).e == something then ...

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

Could possibly add a __eq function so 'maybe(a).b.c == 123' works as
expected.

Scott