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.
Programming in Lua | ||
Part II. Tables and Objects Chapter 11. Data Structures |
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 endany 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 endHowever, 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).
Copyright © 2003–2004 Roberto Ierusalimschy. All rights reserved. |