lua-users home
lua-l archive

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


On 12/22/2014 06:58 PM, Antonio Scuri wrote:
>  Hi,
> 
>   I would like to write something like this *in a single line*:
> 
> y = (x == nil)? x: x + 1
> 
>   If I do this:
> 
> y = testfunc(x == nil, x, x+1)
> 
>   and implement the "if" inside the function, I have the problem that
> both expressions are evaluated before calling the function, and the
> second expression will produce an error when x is nil.
> 
>   I'm not seeing the solution. Is this possible?
> 
> Thanks,
> Scuri
> 

You can do this with 'and' and 'or' operators. What in C you'd write as
    a ? b : c
in Lua you can write like
    a and b or c
the only issue being that b cannot be false-y.

In your case, however, b is false-y, so you have to reorder your
statement as
    x ~= nil and x + 1 or x

For more information regarding this problem see the respective page on
lua-users wiki: http://lua-users.org/wiki/TernaryOperator

-- 
/* mniip */
Apologies if there's a double message around here somewhere

-- 
/* mniip */