This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Xtansia's profile picture

[Advanced Tip]The Lua Equivalent Of Java's Ternary Operator

Started by Xtansia, 26 August 2012 - 02:57 AM
Xtansia #1
Posted 26 August 2012 - 04:57 AM
Warning this is aimed towards advanced users.

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 valueIfTrue
But 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 A
This evaluates that if A is less than B then minValue is assigned A otherwise minValue is assigned B

Notes on the functionality of 'and' &amp; '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 on 23 January 2013 - 11:45 PM
djblocksaway #2
Posted 26 August 2012 - 06:41 AM
Sexy :D/>/>
FuzzyPurp #3
Posted 26 August 2012 - 06:44 AM
HollaLua
BigSHinyToys #4
Posted 26 August 2012 - 06:45 AM
This is the most use full tip ever thanks + 1