Hi guys,
Quite often when looking at code I’ll often see something like this…
items[i].object:translate(0, (i \> 1) and items[i-1].object.contentHeight \* (i-1) or 0)
What I don’t get is the second half of the parameters ( from the i>1 onwards). Could someone help me make sense of it please.
Somebody will probably be more eloquent than me but I use it to safeguard the code from unexpected results. The things in between the “ands” have to be true if not the item after the “or” is provided. Since nil is not true it also works with strings and nils which is very convenient (at least for me). Here is a simple example:
local thisIsNil = nil local thisIsNot = "Not Nil" print("Test:", (thisIsNil or thisIsNot))
Jan 12 10:59:34.540 Test: Not Nil
This is a code shortcut / very similar to the ternary operator (often using the symbol ?) in other languages like C/++ etc.
What it does is an either/or selection/execution of code after the “and” and “or” depending on the evaluation of the expression before the “and”.
I.e. an extended form of the code in your sample would be
[lua]
local function _dummy_func( i )
if i > 1 then
return items[i-1].object.contentHeight * (i-1)
else
return 0
end
end
items[i].object:translate(0, _dummy_func(i) )
[/lua]
@Michael Flad
That’s brilliant. A nice easy to understand explanation. Many thanks.
Somebody will probably be more eloquent than me but I use it to safeguard the code from unexpected results. The things in between the “ands” have to be true if not the item after the “or” is provided. Since nil is not true it also works with strings and nils which is very convenient (at least for me). Here is a simple example:
local thisIsNil = nil local thisIsNot = "Not Nil" print("Test:", (thisIsNil or thisIsNot))
Jan 12 10:59:34.540 Test: Not Nil
This is a code shortcut / very similar to the ternary operator (often using the symbol ?) in other languages like C/++ etc.
What it does is an either/or selection/execution of code after the “and” and “or” depending on the evaluation of the expression before the “and”.
I.e. an extended form of the code in your sample would be
[lua]
local function _dummy_func( i )
if i > 1 then
return items[i-1].object.contentHeight * (i-1)
else
return 0
end
end
items[i].object:translate(0, _dummy_func(i) )
[/lua]
@Michael Flad
That’s brilliant. A nice easy to understand explanation. Many thanks.