lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hello list,

In a document I found on the Kepler website[1] I read that you can use
logical operators "and" and "or" to emulate a ternary operator like in
C. An expression of type "x ? y : z" where "y" is not a false value
(ie, y is different of "nil" and "false") can be represented in Lua
as:

x and y or z

For example, we can initialize a variable "s" with a given value if
"n" is an even number and other value otherwise:

s = (n % 2 == 0) and "even" or "odd"

This syntax make a lot of sense for me :-)

Thanks,
Carlos.

[1] http://www.keplerproject.org/docs/apostila_lua_2008.pdf (in portuguese only)


On Tue, Sep 14, 2010 at 7:19 PM, Pierre Chapuis <catwell@archlinux.us> wrote:
>
> "Paul Hudson" <phudson@pobox.com> a écrit :
>
>>Yuk. Just use if/then/else, in that case.
>
> I also don't like evaluating code but if/then/else has scoping problems. Here's a solution that works but is still not elegant:
>
> a = (function(b) if b then return x else return y end end)(b)
>
> --
> Pierre Chapuis
>
>