array

Arrays in Lua simply are tables indexed with integers. Therefore, arrays do not have a fixed size, they grow as needed.

local arr = {} -- new array, same as empty table

An array can be initialized with values:

local days = {"Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday"}

print(days[1]) -- prints "Sunday"

You can use # prefix to return the size of an array:

print(#days) -- prints "7"

⚠️ In Lua, array indexes start at 1 !

local arr = {}
arr[1] = "hello"
arr[2] = "world"

print(#arr) -- prints "2"

arr[0] = "something"

print(#arr) -- still prints "2", because index 0 is not considered

This is how you can you loop over all values in an array:

local arr = {"hello", "world", "!"}

for index in pairs(arr) do
  print(arr[index])
end
-- prints "hello", "world" & "!"

-- OR

for index, value in ipairs(arr) do -- using ipairs to get index & value
  print(value)
end
-- also prints "hello", "world" & "!"