Auto-growing Tables

We have learnt how tables could be useful to store some predefined values (e.g. colors) for later picking them by numeric index. But greater powers lie in the fact that we can change values inside array or even add new values.

Regard the task: user is asked to enter several numbers, and program should print them in backwards order. We don't know how many numbers user wants to input - instead let's agree that entering 0 means end (and this 0 shouldn't be printed).

How to deal with that? We need to create a table, empty at beginning.

Then we'll ask user to enter values in a loop. After every input let's add new value to the table. If we do it properly (sequentially) the size is automatically recalculated. After end of input we'll only need to print it from the highest index to lowest:

values = {}       -- empty table in variable "values"
while true do     -- endless loop, we'll "break" from inside
    x = io.read('*n')
    if x == 0 then
        break     -- magic way to get out of the loop
    end
    values[#values + 1] = x
end

for i = #values,1,-1 do
    print(values[i])
end

The most interesting line is appending new value to the table. As you see, we use #values + 1 for index. So when there are 0 elements, new index is 1, when there are N elements we always insert at position N+1. In this way size (e.g. #values) is properly incremented upon each addition so everything works just as we need.

Play with this code. When you think you understand everything, here are few more problems for exercise:

If you feel some of them are bit too hard for you right now, don't despair. Either simply skip, or try solve more general problems on this site, picking less difficult from the top.