This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.
The fourth edition targets Lua 5.3 and is available at Amazon and other bookstores.
By buying the book, you also help to support the Lua project.


11.1 – Arrays

We implement arrays in Lua simply by indexing tables with integers. Therefore, arrays do not have a fixed size, but grow as we need. Usually, when we initialize the array we define its size indirectly. For instance, after the following code

    a = {}    -- new array
    for i=1, 1000 do
      a[i] = 0
    end
any attempt to access a field outside the range 1-1000 will return nil, instead of zero.

You can start an array at index 0, 1, or any other value:

    -- creates an array with indices from -5 to 5
    a = {}
    for i=-5, 5 do
      a[i] = 0
    end
However, it is customary in Lua to start arrays with index 1. The Lua libraries adhere to this convention; so, if your arrays also start with 1, you will be able to use their functions directly.

We can use constructors to create and initialize arrays in a single expression:

    squares = {1, 4, 9, 16, 25, 36, 49, 64, 81}
Such constructors can be as large as you need (well, up to a few million elements).