Changing Variables
The value of a variable can change while the program runs. Emma sells eggs, and she has more coins:
local coins = 120
print("Coins: " .. coins)
coins = coins + 15
print("Coins: " .. coins)This prints:
Coins: 120
Coins: 135In math, coins = coins + 15 wouldn't make sense. But in programming, = means “store”: first, Lua calculates the right side with the current value (120 + 15), and then it stores the result, 135, in coins. The old value is gone. The program runs from top to bottom, so the first print still printed 120.
Notice that the third line has no local. You write local only once, when you create the variable. To change it, write just its name, = and the new value. local coins = coins + 15 would create a second variable with the same name. In a short program like this one, you wouldn't notice the difference, but in the lessons on conditions and loops, the change would get lost.
You can calculate the new value from other variables too. And a variable stores a number, not the calculation that gave it:
local carrots = 10
local potatoes = 5
local crops = carrots + potatoes
carrots = 20
print(crops)This prints:
15When Lua got to the line with crops, it calculated 10 + 5 and stored 15. Changing carrots later doesn't change crops.
Many languages have shortcuts like coins += 15 (add 15) or coins++ (add 1). Standard Lua has none of them. (Roblox's Luau has +=, but that's a different Lua; more about it at the end of the course.) In Lua, you always write the whole thing, coins = coins + 15:
local coins = 120
coins += 15Lua reports:
main.lua:2: syntax error near '+'As you know from the first lesson, a syntax error means that the program isn't written according to Lua's rules. Near '+' tells you where Lua got lost: it understood coins, but didn't expect a + after it. As with every syntax error, nothing runs, not even the lines above it.
You get the same error when you write only coins + 15 on a line. Lua doesn't allow a calculation whose result isn't stored anywhere, so at least it tells you that you forgot the coins =.
Instructions
Run the program. Lines 7 and 8 are written the way some other languages allow, and Lua reports an error. Fix both lines the Lua way: line 7 adds 4 * 5 to coins, and line 8 subtracts 4 from carrots. The program then prints:
Coins: 50, carrots: 10
Coins: 70, carrots: 6With the money, Emma buys 3 packets of pumpkin seeds for 5 coins each. At the end of the program, subtract their price from coins (let the program calculate 3 * 5), and print the same line once more:
Coins: 50, carrots: 10
Coins: 70, carrots: 6
Coins: 55, carrots: 6Before she goes home, Emma pulls 8 more carrots from the field. Add them to carrots, and print the line again:
Coins: 50, carrots: 10
Coins: 70, carrots: 6
Coins: 55, carrots: 6
Coins: 55, carrots: 14Start programming for free
2/10