Many languages support a feature called ternary operator (although that's technically a broader term) which allows you to simplify if condtions that are only used to decide which of two values to return/assign.
Consider the following code:
Code: Select all
local x = 42
local y
if x > 7 then
y = 'greater than seven'
else
y = 'no'
end
In other languages the assignment of y could be written like this:
Code: Select all
y = x > 7 ? "greater than seven" : "no" -- C, Java, C#, ...
and and or
Now the thing is, that Lua does not have a dedicated ternary operator. However, we can mimic its behavior by using the and and or binary comparison operators. In Lua these behave a bit differently than in other language in terms of what they return. To understand why that is we have to take a closer look at what Lua "considers to be true":
Code: Select all
if x then print('x is true') end
For that reason an expression like
Code: Select all
a and b
Similarly
Code: Select all
a or b
Bringing it together
Now we can rewrite the Lua code from above as
Code: Select all
local y = x > 7 and 'great than seven' or 'no'
Expressions
I used an italic font for values because what we're actually talking about here are expressions. The difference is that you can get a value out of an expression, but you don't have to. That makes an huge difference when your expression e.g. contains functions that can modify state somewhere else. If the value of an expression is not needed, it will not be executed. That can be both, useful for optimization but also for error prevention.
An example:
Code: Select all
local function foo()
return 42
end
local y
if foo then
y = foo()
else
y = 0
end
Code: Select all
local y = foo and foo() or 0
Code: Select all
local income = City and City.getIncome() or 0
Default function arguments
You often want to have some sort of "default" values for function parameters that were not provided by the caller (and are therefore nil). You can do that conveniently by using the behavior of the or operator:
Code: Select all
function foo(str, tbl, num)
str = str or 'I was not set' -- Use 'I was not set' as default value for str
tbl = tbl or {} -- Create a table if none was given
num = num == nil and 42 or num -- Use 42 if num was not provided; note that we have to be careful if we want num to be able to be 0
-- Do something with str, tbl and num...
end
-- Can be called in different ways:
foo()
foo('hi')
foo('hi', { 1, 2, 3 })
foo('hi', { 1, 2, 3 }, 7)