lua-users home
lua-l archive

Re: Lookup nil table index

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


Hello,
I'm working on code with quite deep tables. When referring to an element
in the table, I use the table keys joined by dots, eg:
	a = thing.foo.bar.this.that
When one of the indicated elements does not exist, an error is generated
for apperent reasons: attempt to index nil value.
I use a little function to do the deep table lookup, if a key could be nil:
--returns object indexed by 1..n keys
--returns nil if a key is nil
function indextbl(obj,...)
	local idx={...}
	for i=1,select('#',...) do
		local k=idx[i]
		if obj==nil or k==nil then
			return nil
		else
			obj=rawget(obj,k)
		end
	end
	return obj
end
You can use it as follows:
a = indextbl(thing,'foo','bar','this','that')
BR,
Michael

AltStyle によって変換されたページ (->オリジナル) /