The else Branch
An if statement runs its block only when the condition is true. Often, you also want to do something when it's false. That's what else (“otherwise”) is for:
local weather = "cloudy"
if weather == "rainy" then
print("The rain waters the field")
else
print("Emma waters the field")
endThis prints:
Emma waters the fieldThe condition is false, so the program skips the first block and runs the block after else. The two blocks are called branches: like a path that splits in two, the program always takes exactly one of them. It never runs both, and it never skips both.
else stands on its own line, indented like its if, and the whole statement still ends with a single end. else has no condition and no then: it takes every case the if didn't. If you give it a condition anyway, as in else weather ~= "rainy" then, Lua reports syntax error near '~='.
Branches often give a variable its value. Create the variable before the if, and in the branches only change it:
local weather = "sunny"
local buckets
if weather == "sunny" then
buckets = 12
else
buckets = 4
end
print("Buckets of water: " .. buckets)This prints:
Buckets of water: 12local buckets without a value creates the variable with the value nil, and one of the branches then stores a number in it. Don't write local again in the branches. A variable created with local inside a block exists only until the end of that block:
local weather = "sunny"
if weather == "sunny" then
local buckets = 12
end
print("Buckets of water: " .. buckets)main.lua:5: attempt to concatenate a nil value (global 'buckets')After end, the buckets from the block is gone. Lua then looks for a global variable called buckets, finds none, and gets nil, just as with a typo in a name.
Instructions
Run the program: it prints the weather and then ends with an error, because when it isn't sunny, buckets stays nil. Add an else branch that sets buckets to 4. The program then prints:
Weather: rainy
Buckets of water: 4Change weather to "sunny" and run the program again. Now the condition is true, so the program takes the first branch and prints:
Weather: sunny
Buckets of water: 12Start programming for free
3/10