[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: indexed expression not a table
- From: Roberto Ierusalimschy <roberto@...>
- Date: Thu, 21 Oct 1999 15:54:41 -0200
> I guess this makes sense, but for my application I would like a
> missing subfield to be considered nil, because I view x.b.e to really
> be a value reference of table x indexed by "b" and "e" (x["b"]["e"]),
> so that element is nil if "e" doesn't exist.
Tables in Lua are objects. Lua does not have the notion of matrices; so,
x.b.e is (x.b).e: First get the field "b" from the object "x", then get the
field "e" from the resulting object (not from "x" any more). If the result
of x.b is nil (or 2, in your particular example), when you try to get the
field "e" from nil (or from a number) you get the error. (At this time, Lua
does not know that the nil came from a previous indexing.) To change that,
you can change the semantics of (x.b), so that it returns an empty table:
x = {a=1}
t = newtag()
settag(x, t)
settagmethod(t, "index", function (tab, ind) tab[ind]={}; return tab[ind] end)
print(x.b.e) --> nil
print(x.a) --> 1
print(x.a.e) -- still an error, since x.a is not a table (nor nil)
If your keys are strings, you can also change your representation of matrices.
Instead of a table of tables, you can use a single table, with the indices
concatenated with a convenient separator in between; something like
x["e@i"] to represent x.e.i
x[e.."@"..i] to represent x[e][i]
It is more verbose, but maybe this is closer to what you want.
-- Roberto