Lua is a nice programming language, which allows for readable and concise code. One of my favorite idioms in the language is this:
x = a and b or c
which usually works like the C ternary operator, “a ? b : c”, but in a more readable fashion. This works in Lua because the “and” and “or” operators return their matching value when they get a “true” value (anything other than false and nil).
One thing to keep in mind though, is that this is really “and and b or c” and not “a then b else c”. There’s one big difference: when you want to have nil or false in your “then” value.
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio > = true and 10 or 20 10 > = false and 10 or 20 20 > = true and nil or 20 20
An ugly alternative is to do “not a and c or b”, like this:
> = not true and 20 or 10 10 > = not false and 20 or 10 20 > = not true and 20 or nil nil
But at this point it’s better just to use an “if” statement. (This hack works around the then-as-nil case, but not else-as-nil, of course.)
So, keep in mind that you should use the “a and b or c” construct as if-then-else only if you know that your “b” value is not nil or false.
It’s better, however, to use this construct for what it is. This behavior is not flawed, it is just different, and it has its own uses. For example, it is very useful to check if a table exists:
x = tbl and tbl.key
And to define fallback values:
x = tbl and tbl.key or "missing!"
Note that the above line reads naturally, and you wouldn’t be able to do that with one “?:” operator in C.
Fill out the form below to add your own comments.