Engineer, on 03 March 2013 - 11:35 AM, said:
I am learning Java now and there you have two kinds of if statements, the one that is printable:
In Java:
System.out.println( ( random_var > 1)? "Heey guys" : "See you later guys" );
just an FYI there are not 2 kinds of if statements. there is if:
if ( <condiftion> ) {
<if true>
}
else {
<if false>
}
and there is what is called a
ternary operator:
<condition> ? <if true> : <if false>
A ternary operator is far more than a 'printable' if statement. it can be used in assignment statements too.
Where in an if statement you might do this
if ( player.collided ) {
player.location.x = world.teleporter.location.x
}
else {
player.location.x = player.location.prevX
}
it can also use a ternary operator by using the following
player.location.x = ( player.collided ? world.teleporter.location.x : player.location.prevX )
So really a ternary operator is a shortened form of an if else statement.
Now as Eric posted a ternary in Lua can be done with
<condition> and <if true> or <if false>
now there is just another thing I would like to point out, since i have seen people do it before. lets say we have this code
local args = { ... } -- runtime arg that is the 'depth' the user wants
local depth
if args[1] ~= nil then
depth = args[1]
else
depth = 5
end
this would set a default depth if one is not supplied. so now we make it nicer by using Lua's form of the ternary
local args = { ... }
local depth = args[1] ~= nil and args[1] or 5
so this looks about right and done. well we can go a step further, obviously we are saying if a depth has been supplied use it, or make it 5. so that can be simplified to
local args = { ... }
local depth = args[1] or 5
Hope this helped explain a few things.