What Counts as True

A condition doesn't have to be a comparison. After if, you can write any value, and Lua decides whether it counts as true. Lua's rule is short: false and nil count as false, and everything else counts as true, even the number 0 and the empty text "":

if 0 then
    print("0 counts as true")
end
if "" then
    print("An empty text counts as true")
end
if nil then
    print("nil counts as true")
end

This prints:

0 counts as true
An empty text counts as true

Remember this well, especially if you've met another language: in Python, JavaScript or C, 0 counts as false. In Lua, it doesn't, and that's easy to get wrong:

local seeds = 0
if seeds then
    print("Emma plants the seeds")
else
    print("Emma has no seeds")
end

This prints:

Emma plants the seeds

Emma has no seeds, but 0 counts as true. To ask whether there are any seeds, compare: if seeds > 0 then.

So what is if seeds then good for? It asks “does seeds have a value?”, that is, “isn't it nil?”. That's useful, because some functions give nil when they fail. You know tonumber: it gives nil when the text isn't a number:

local answer = "a dozen"
local eggs = tonumber(answer)
if eggs then
    print("Eggs: " .. eggs)
else
    print("That's not a number: " .. answer)
end

This prints:

That's not a number: a dozen

With answer = "12", eggs would be 12, and the program would print Eggs: 12. not follows the same rule, and it always gives a boolean: not nil is true, and not 0 is false. So if not eggs then means “if eggs is nil” (or false).

One more trap: if seeds == true then isn't the same as if seeds then. == compares exactly, and a number is never equal to the boolean true, so 5 == true is false. Just leave == true out.

Instructions

Run the program: it prints Emma plants 0 seeds. Fix the condition so that Emma plants only when she has more than 0 seeds. The program then prints:

Emma buys new seeds

Grandpa Joe wrote down how many eggs he wants, but as a text, note. At the end of the program, convert it with tonumber and store the result in a local variable eggs. Then write an if statement whose condition is just eggs. If it has a value, print Grandpa Joe wants 14 eggs (with the number from eggs); otherwise, print Emma can't read the note: followed by the note. The program prints:

Emma buys new seeds
Grandpa Joe wants 14 eggs

Change note to "fourteen". tonumber can't turn a word into a number, so eggs is nil, and the program prints:

Emma buys new seeds
Emma can't read the note: fourteen

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

6/10