[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Depth indexing of nil
- From: Simon Green <Simon.Green@...>
- Date: Thu, 9 Jul 2015 13:10:20 +1200
Hi all,
I’m relatively new to Lua and I feel like this should have already been answered, but if so I cannot find the right combination of words to type into Google to find it.
Suppose I have a nested structure of tables a to e such that I could have a.b.c.d.e. However, anything from b down might not actually exist. So, ‘a’ could be empty, or ‘b’ could be … all the way down to ‘d’ not having an ‘e’.
I want to use the value of ‘e’, if it exists. If it doesn’t, that’s fine, I do something else. This:
if a.b.c.d.e == something then
something-else
end
only works if everything down to e exists. If anything else doesn’t, then Lua spits the dummy and tells me I’m indexing a nil value. This is technically correct, but actually, I don’t care. So what I end up having to do is:
if a and a.b and a.b.c and a.b.c.d and a.b.c.d.e and a.b.c.d.e == something then
something-else
end
In Python, if I referenced a.b.c.d.e and b didn’t exist I’d simply get an IndexError or KeyError exception. Noting that there are no exceptions in Lua, is there some other way I can avoid having thousand-word-long lines every time I want an if statement? Basically, what I'm asking is, if 'b' doesn't exist, is there a way to have a.b.c.d.e == x just return false instead of break my entire program?
Cheers
Simon
Simon Green
Senior VAS Engineer
Two Degrees Mobile Limited
==========================
(M) 022 023 0240
(P) +64 9 919 7057
www.2degreesmobile.co.nz
Two Degrees Mobile Limited | 47-49 George Street | Newmarket | Auckland | New Zealand|
PO Box 8355 | Symonds Street | Auckland 1150 | New Zealand | Fax +64 9 919 7001
Disclaimer
The e-mail and any files transmitted with it are confidential and may contain privileged or copyright information. If you are not the intended recipient you must not copy, distribute, or use this e-mail or the information contained in it for any purpose other than to notify us of the error. If you have received this message in error, please notify the sender immediately, by email or phone (+64 9 919 7000) and delete this email from your system. Any views expressed in this message are those of the individual sender, except where the sender specifically states them to be the views of Two Degrees Mobile Limited. We do not guarantee that this material is free from viruses or any other defects although due care has been taken to minimize the risk