Arrays in Lua

In Lua, an array is typically implemented using tables. Lua tables are versatile and can be used to represent various data structures, including arrays. Here’s how we can work with array-like structures in Lua:

-- In Lua, we can create an array-like structure using a table
-- By default, table elements are nil
local a = {}
for i = 1, 5 do
    a[i] = 0
end
print("emp:", table.concat(a, " "))

-- We can set a value at an index using the
-- table[index] = value syntax, and get a value with
-- table[index]
a[5] = 100
print("set:", table.concat(a, " "))
print("get:", a[5])

-- The # operator returns the length of a sequence in Lua
print("len:", #a)

-- Use this syntax to declare and initialize a table
-- in one line
local b = {1, 2, 3, 4, 5}
print("dcl:", table.concat(b, " "))

-- In Lua, you don't need to specify the size upfront
b = {1, 2, 3, 4, 5}
print("dcl:", table.concat(b, " "))

-- To create a sparse array in Lua, you can simply assign values to specific indices
b = {[1] = 100, [4] = 400, [5] = 500}
print("idx:", table.concat(b, " ", 1, 5))

-- In Lua, multi-dimensional arrays are represented as tables of tables
local twoD = {}
for i = 1, 2 do
    twoD[i] = {}
    for j = 1, 3 do
        twoD[i][j] = i + j - 2
    end
end
print("2d:", twoD)

-- You can create and initialize multi-dimensional
-- tables at once too
twoD = {
    {1, 2, 3},
    {1, 2, 3}
}
print("2d:", twoD)

Note that tables in Lua are printed in the form table: 0x... when using print. To display the contents, we use table.concat for one-dimensional tables and a custom print function might be needed for multi-dimensional tables.

When you run this Lua script, you should see output similar to:

$ lua arrays.lua
emp: 0 0 0 0 0
set: 0 0 0 0 100
get: 100
len: 5
dcl: 1 2 3 4 5
dcl: 1 2 3 4 5
idx: 100 0 0 400 500
2d: table: 0x...
2d: table: 0x...

Remember that Lua tables are more flexible than traditional arrays. They can have non-integer keys and don’t require contiguous indices. This example focuses on using them in an array-like manner for comparison with the original example.