Page 1 of 1

Ternary Operator

Posted: Sun Feb 10, 2013 5:46 pm
by Raylin
Hey, guys.
Does Lua have a quick fix for the ternary operator?
Or do I need to set some metatables for it?

Re: Ternary Operator

Posted: Sun Feb 10, 2013 6:18 pm
by Saegor
i don't understand your question

wath fix do you speak about ?

the fact that

Code: Select all

v = v and false or true
don't work as expected ?

Re: Ternary Operator

Posted: Sun Feb 10, 2013 6:30 pm
by Raylin
Saegor wrote:the fact that

Code: Select all

v = v and false or true
don't work as expected ?
Well, it looks like that only returns true or false upon testing v.
I need a operator that can execute a piece of code if something is true else, execute another piece of code.

Re: Ternary Operator

Posted: Sun Feb 10, 2013 6:34 pm
by Saegor
Raylin wrote:
Saegor wrote:the fact that

Code: Select all

v = v and false or true
don't work as expected ?
Well, it looks like that only returns true or false upon testing v.
I need a operator that can execute a piece of code if something is true else, execute another piece of code.
in fact it don't work because the second argument is false. it's the main problema with ternary operators in Lua

for your problem, what do you think of

Code: Select all

function love.update()
some_function(condition and "instruct_1" or "instruct_2")
end


function some_function(instruct)

if instruct == "instruct_1" then
...
end

elseif instruct == "instruct_2" then
...
end
end
ps : some issues with firefox, no more tabbing :huh:

else, explain maybe more accurately your problem

Re: Ternary Operator

Posted: Sun Feb 10, 2013 6:50 pm
by Raylin
I'm trying to emulate the same functionality that the question mark ((test)?a:b) would give.

Re: Ternary Operator

Posted: Sun Feb 10, 2013 6:59 pm
by markgo
Have you tried this? I'm not sure what is so difficult.

Code: Select all

v = (v and func1() or func2()) and v
or

Code: Select all

if v then
...
else
...
end

Re: Ternary Operator

Posted: Sun Feb 10, 2013 10:43 pm
by Robin
Raylin wrote:I'm trying to emulate the same functionality that the question mark ((test)?a:b) would give.
In Lua, that would be test and a or b, but only if a is always a truthy value. If you can't guarantee that, you're stuck using if-statements.

Re: Ternary Operator

Posted: Mon Feb 11, 2013 1:30 am
by Raylin
Thanks, guys. Robin's answer pretty much sealed the deal. :)