Changing Items

An item of a list works like a variable: you can give it a new value with =. On the left, write the list's name and the index in square brackets, just as when you read the item:

local plots = {"carrot", "potato", "pumpkin"}
plots[2] = "tomato"
print(plots[1], plots[2], plots[3])

This prints:

carrot	tomato	pumpkin

The second item is now "tomato", and the old "potato" is gone. The other items stay as they were. Numbers in a list change the same way. Lua has no +=, so you write the item on both sides:

local eggs = {4, 6, 5}
eggs[3] = eggs[3] + 2
print(eggs[3])

This prints:

7

Don't write == instead of =. plots[2] == "tomato" is a comparison, not a command, and on a line of its own, it ends with syntax error near '=='.

Adding an item to the end. The place right after the last item has the index #plots + 1. When you assign a value there, the list grows by one item:

local plots = {"carrot", "potato"}
plots[#plots + 1] = "wheat"
plots[#plots + 1] = "corn"
print(#plots, plots[3], plots[4])

This prints:

4	wheat	corn

After the first assignment, the list has three items, so the second one puts "corn" at index 4. This way, you can also fill a list that starts empty: local harvest = {}, and then harvest[#harvest + 1] = … as many times as you need.

Don't leave holes. A list should have its items at the indexes 1, 2, 3… with no gaps. If you assign an item further away than #plots + 1, or set an item in the middle to nil, the list gets a hole, and # stops being reliable:

local crops = {"carrot", "potato", "pumpkin", "wheat"}
crops[2] = nil
print(#crops)
local more = {"carrot", "potato", "pumpkin"}
more[5] = "corn"
print(#more)

This prints:

4
3

The first list has only three crops left, but # says 4. The second one has four crops, but # says 3: it doesn't see "corn" at all. With a hole, # may count up to the hole or past it, and Lua doesn't promise which. So add items only at #t + 1, and remove them the way the next exercise shows.

Instructions

The potatoes have been harvested, and Emma has planted tomatoes in their place. Below the print, change the second item of plots to "tomato".

Emma has dug a new plot for wheat. Add "wheat" to the end of the list, at the index #plots + 1.

At the end of the program, print the number of plots, the second plot and the last one, each on its own line. Get the last one with #plots:

Plots: 4
Second: tomato
Last: wheat

Start programming for free

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

Or sign up with:

3/11