Programming in Lua | ||
Part II. Tables and Objects Chapter 11. Data Structures |
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).
Programming in Lua |
No comments:
Post a Comment