7 8 9 10 11

Arrays

100

Arrays or lists in Lua — is just a special case of Lua table. This is similar to PHP arrays.

Lua array is a table which has serial integer keys. Unlike many other programming languages, index of the first element in Lua array is 1, not 0.

You can define Lua array in the following way:

numbers = {1, 2, 3, 4, 5}

You can store values of different types within the same array:

items = {100, "Sam", true, function () print("Hello") end}

items[4]()

Array length can be optained with # operator:

primes = {2, 3, 5, 7, 11}

print(#primes)

You can iterate over an array in the following way:

primes = {2, 3, 5, 7, 11}

for index, value in ipairs(primes) do
    print("primes[" .. index .. "]: " .. value)
end

Running the example above you will see:

primes[1]: 2
primes[2]: 3
primes[3]: 5
primes[4]: 7
primes[5]: 11

As you can see, array index starts with 1.

Rate this post:
Lesson 9
Lesson 11
Share this page:

Learning plan

What kind of functions are there and how to write them
How to write tail recursion in Lua properly
9. Strings
How to define and work with strings
10. Arrays
How to deal with arrays or lists
11. Tables
Table is a general Lua data structure, it's all about tables