Corona SDK Pro Tip of the Day #8
Inline conditionals

Use "inline conditionals" for default values.

In other languages there is ternary operator ? : . which is often missed in Lua.

However Lua has an equivalent and or statement. You are advised to use it for default values in your functions.

local function newCoin(value, color, size)  
    local coin = {}
    coin.value = value or 1
    coin.color = color or 'gold'
    coin.size = size or 32
    return coin
end  

It has the same logic as

if color then  
    coin.color = color
else  
    coin.color = 'gold'
end  

It works because and or doesn't return true or false. Instead it returns a value, which triggered end of execution of the condition.

So far it was only or statement. and or is useful for example when you need to read a property of an object, but you are not sure if such object exists.

It is also convenient to use it with math.random(1, 2) if you need to choose between two values randomly.

local function newChild(first_name, father, mother)  
    local child = {}
    child.gender = math.random(1, 2) == 1 and 'male' or 'female'
    child.first_name = first_name or (child.gender == 'male' and 'John' or 'Jane')
    child.last_name = father and father.last_name or mother and mother.last_name or 'Orphan'
    return child
end  

Here gender is chosen randomly between 'male' and 'female'.
Next, first name is either John or Jane depending on the gender.
Last name is taken from father if father exists, if there is no father then mother's last name is taken. Lastly if there is no father and no mother, default last name is used - Orphan.

If it's hard to read, you can help yourself with parenthesis.

child.last_name = (father and father.last_name) or (mother and mother.last_name) or ('Orphan')  

When there is no first_name or no father, don't forget to put nil instead of them.

newChild(nil, nil, {first_name = 'Milla', last_name = 'Jovovich'})  

Another good place to use inline conditionals is inside strings. When you concatenate such values, you must use parenthesis.

print('Child\'s father: ' .. (child.father or 'unknown') .. '.')  

Indie Game Developer