The Java ternary operator let's you assign a value to a variable based on a boolean expression (either a boolean field, or a statement that evaluates to a boolean result).
Syntax[Java]:
result = condition ? valueIfTrue : valueIfFalse; // Also can be used when calling methods: doSomeStuff(condition ? valueIfTrue : valueIfFalse);
Example[Java]:
minValue = ( A < B ? A : B );This evaluates that if A is less than B then minValue is assigned A otherwise minValue is assigned B
This can be expanded to be written as
Example[Java]:
if ( A < B ) {
minValue = A;
} else {
minValue = B;
}
See how much smaller it was written with the ternary operator.
But how can we write this in Lua you ask?
Well most likely if set the task you would write this
Example[Lua]:
if A < B then minValue = A else minValue = B end
Well I'm here to tell you there is another way using the syntax
Syntax[Lua]:
result = (condition and valueIfTrue) or valueIfFalse doSomeStuff((condition and valueIfTrue) or valueIfFalse)Flaws: With this syntax if valueIfTrue is nil or false then valueIfFalse will be returned no matter what, but if valueIfTrue needs to be false or nil you can invert the syntax like so
Syntax[Lua]:
result = (not condition and valueIfFalse) or valueIfTrueBut the flaw in this syntax is that if valueIfFalse is false or nil then valueIfTrue will be returned no matter what
So you must choose carefully.
Knowing this we can simplify the above if statement to
Example[Lua]:
minValue = ( A < B ) and A or B --And Inverted: minValue = not ( A < B ) and B or AThis evaluates that if A is less than B then minValue is assigned A otherwise minValue is assigned B
Notes on the functionality of 'and' & 'or' in the above examples
The way these two keywords are used above could be represented by these two functions
And[Lua]:
function and( condition, A ) if condition then --If condition evaluates true/non nil return A --Return the A value else --If condition evaluates false/nil return condition --return false/nil end end
Or[Lua]:
function or( andResult, B ) if not andResult then --If the result of the and was false/nil return B else return andResult end end
Edited by tomass1996, 24 January 2013 - 12:45 AM.











