lua-users home
lua-l archive

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


On 02/23/2017 12:06 PM, Dirk Laurie wrote:
> I want `a.b.c.d.e`. I'm going to test for nil, and I don't care
> at what level the missing index is.
> 
> 1.   x = a and a.b and a.b.c and a.b.c.d and a.b.c.d.e
> 2.   x = has(a,"b.c.d.e") with
> function has(a,idx)
>   local j,k = idx:match"([^.]+)%.(.*)"
>   if not k then return a[idx]
>   else return has(a[j],k)
>   end
> end
> 3, debug.setmetatable(nil,{__index=function() return nil end})
> x = a.b.c.d.e

4: (Shown this before)
-- 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

Scott