The Length of a List

You know the operator # from texts: #"carrot" is 6, the length of the text. Put it in front of a list, and it gives you the number of items, the length of the list:

local crops = {"carrot", "potato", "pumpkin"}
print(#crops)
print("Crops: " .. #crops)
print(#{})

This prints:

3
Crops: 3
0

An empty list has the length 0. # gives an ordinary number, so you can calculate with it: #crops + 1 is 4. Don't mix up #crops and #crops[1], though. The second one is the length of the first item, the text "carrot": 6.

The length also tells you where the last item is. Indexes go from 1 to the number of items, so the last index is the length itself: a list of 3 items has the indexes 1, 2 and 3. The last item is crops[#crops]:

local crops = {"carrot", "potato", "pumpkin"}
print(crops[#crops])
print(crops[#crops - 1])

This prints:

pumpkin
potato

Lua first works out the index in the square brackets (#crops is 3, and 3 − 1 is 2) and then reads the item at that index. So crops[#crops - 1] is the second to last item.

Why not just write crops[3]? Because lists change. In the next exercises, you'll add and remove items, and programs often work with lists they didn't create themselves, of any length. crops[#crops] is always the last item, however long the list is. With crops[3], the program would keep printing the third crop even after Emma plants a fourth one.

A common mistake is to go one step too far. crops[#crops + 1] is the place right after the last item, where there's nothing yet:

local crops = {"carrot", "potato", "pumpkin"}
print("Last crop: " .. crops[#crops + 1])
main.lua:2: attempt to concatenate a nil value (field '?')

This time, the message says field '?'. Lua describes the index only when it's a number written in the code; here, it had to calculate it first. The place #crops + 1 will come in handy, though: in the next exercise, you'll add a new item exactly there.

Instructions

Below the print, print the number of seed bags in the list, using #: Bags: 5.

Create a local variable last with the last item of seeds. Get it with #, not with the number 5.

Print it: Last: wheat.

Finally, print the second to last bag the same way, with #seeds - 1: Second to last: strawberry.

Start programming for free

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

Or sign up with:

2/11