syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me

Question:
In Lua how to do ternary expression?

Most interpreted languages have a ternary expression syntax.

The intent behind ternary expression syntax is to pack if-then-else logic into one line of code.

First I show the logic I want:
dan@hp ~/ks/b/lua $
dan@hp ~/ks/b/lua $ lua
Lua 5.3.0  Copyright (C) 1994-2015 Lua.org, PUC-Rio
> a = 1
> b = 2
> x = 3
> y = 4
> if a == b then
>> return x
>> else
>> return y
>> end
4
>
> b = 1
> if a == b then
>> return x
>> else
>> return y
>> end
3
>
>
dan@hp ~/ks/b/lua $
dan@hp ~/ks/b/lua $
I can pack the above if-then-else chunk into one line of syntax:
dan@hp ~/ks/b/lua $
dan@hp ~/ks/b/lua $ lua
Lua 5.3.0  Copyright (C) 1994-2015 Lua.org, PUC-Rio
>
> a = 1
> b = 2
> x = 3
> y = 4
>
> ((a == b ) and x or y)
4
>
> b = 1
>
> ((a == b ) and x or y)
3
>
dan@hp ~/ks/b/lua $
dan@hp ~/ks/b/lua $


syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me