nil: No Value
Sometimes a variable has no value. Lua has a special value for that, nil, which means “nothing”. A variable that you create without = and a value holds nil:
local strawberries
print(strawberries)
print("Strawberries:", strawberries)This prints:
nil
Strawberries: nilnil comes in handy for things that aren't known yet or aren't there. You can also store it in a variable yourself, strawberries = nil, when the variable shouldn't hold anything anymore. But you can't calculate with nil, and you can't join it to a text:
local coins
print("Coins: " .. coins)Lua reports:
main.lua:2: attempt to concatenate a nil value (local 'coins')Read the message from the end. (local 'coins') is the variable: a local one, called coins. a nil value is what it held. And attempt to concatenate is what Lua tried to do with it: join it to a text (concatenate means join). With +, - and the other operators, the message says attempt to perform arithmetic on a nil value (local 'coins'): an attempt to calculate.
The most common source of nil is a typo in a name:
local coins = 120
print(cions)This prints:
nilNo error! Lua didn't find a local variable called cions, so it looked for a global one. There's no such variable either, and a variable that doesn't exist has the value nil. print prints it without complaining. The error comes only when the program does something with the value:
local coins = 120
print("Coins: " .. cions)Lua reports:
main.lua:2: attempt to concatenate a nil value (global 'cions')The word in parentheses gives you a clue:
local: the name is right, but the variable has no value yet. Look for the line where it should have got one.global: all your variables are local, so this one probably doesn't exist. Look for a typo or a wrong capital letter:Coinsis a different name fromcoins.
Instructions
Run the program and read the error. The hens laid 12 eggs today: fix the line that creates eggs, so that the program prints:
Hens: 4
Eggs: 12Add this line at the end of the program, typo included, and run the program:
print("Milk: " .. mlik .. " liters")Read the error. Then fix the name, so that the program also prints the milk that Bella the cow gave:
Hens: 4
Eggs: 12
Milk: 6 litersEmma doesn't know yet how many strawberries she'll pick. Below, create a variable strawberries without a value, and print it after the text "Strawberries:", separated by a comma. Unlike .., a comma works with nil:
Hens: 4
Eggs: 12
Milk: 6 liters
Strawberries: nilStart programming for free
6/10