[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Lookup nil table index
- From: lua@...
- Date: Thu, 30 Nov 2006 16:40:46 +0100
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.
For my application, I'd like such an expression to return a nil value
instead of generating an error. Would it be possible to create such a
behaviour ? I've tried to create something like it with __index on
metatables - this avoids the errors, but returns the table itself
instead of nil :
thing = {}
b = {}
thing.name = "blablah"
b.__index = function(t, k)
return thing
end
setmetatable(thing, b)
printf("%s\n", tostring(thing.name))
printf("%s\n", tostring(thing.foo))
printf("%s\n", tostring(thing.foo.bar))
Can anybody think of a solution for this ?
--
:wq
^X^Cy^K^X^C^C^C^C