Play With Lua!


without comments

Another short post. It’s because I’m working on something.

A lot of languages have a ternary operator, that lets you do this:

int x = foo ? 1 : 2;

It’s an easy way to pack a conditional on to one line, especially useful when giving things default values. Another way is if the if statement returns a value, like in Ruby:

x = if foo

Lua doesn’t have this. The best we can do is just write the if statement, which is unwieldy, especially if it’s several lines long:

local x
if foo then x = 1 else x = 2 end

Well, I noticed that we have another way of doing this. It turns out I’m not the first person to think of this, it was pointed out in the wiki, which is actually probably where I got it from. But it’s useful:

local x = foo and 1 or 2

Because boolean operators return values (other than true/false) and they have precedence like you’d expect, this works perfectly. You can even chain them together:

local x = foo and 1 or bar and 2 or 3

Update: Pierre Chapuis on Twitter points out that this doesn’t work when the first possible value is false:

local x = true and false or 3

He’s right and you should be careful about that.

Written by randrews

May 10th, 2012 at 3:15 pm

Posted in Uncategorized