Jump to content




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

lua java

  • You cannot reply to this topic
3 replies to this topic

#1 Xtansia

  • Members
  • 492 posts
  • LocationNew Zealand

Posted 26 August 2012 - 03: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' & '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.


#2 djblocksaway

    Epic Coderz

  • New Members
  • 397 posts
  • LocationAustralia

Posted 26 August 2012 - 05:41 AM

Sexy :D/>

#3 FuzzyPurp

    Part-Time Ninja

  • Members
  • 510 posts
  • LocationHarlem, NY

Posted 26 August 2012 - 05:44 AM

HollaLua

#4 BigSHinyToys

  • Members
  • 1,001 posts

Posted 26 August 2012 - 05:45 AM

This is the most use full tip ever thanks + 1





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users