-- In Lua, we don't need to import packages like in Go
-- We'll use the print function for output
-- Create an empty table (similar to an uninitialized slice in Go)
local s = {}
print("uninit:", #s, #s == 0)
-- Create a table with initial values (similar to make([]string, 3) in Go)
s = {"", "", ""}
print("emp:", s, "len:", #s)
-- We can set and get values just like with arrays
s[1] = "a"
s[2] = "b"
s[3] = "c"
print("set:", s)
print("get:", s[3])
-- #s returns the length of the table
print("len:", #s)
-- To append elements, we can use the insert function or direct assignment
table.insert(s, "d")
s[#s + 1] = "e"
s[#s + 1] = "f"
print("apd:", s)
-- To copy a table, we need to create a new table and copy elements
local c = {}
for i = 1, #s do
c[i] = s[i]
end
print("cpy:", c)
-- Lua tables support slicing using the unpack function
local function slice(t, start, stop)
local sliced = {}
for i = start, stop or #t do
table.insert(sliced, t[i])
end
return sliced
end
local l = slice(s, 3, 5)
print("sl1:", l)
l = slice(s, 1, 5)
print("sl2:", l)
l = slice(s, 3)
print("sl3:", l)
-- We can declare and initialize a table in a single line
local t = {"g", "h", "i"}
print("dcl:", t)
-- Lua doesn't have a built-in equality function for tables
-- We need to implement our own
local function tablesEqual(t1, t2)
if #t1 ~= #t2 then return false end
for i = 1, #t1 do
if t1[i] ~= t2[i] then return false end
end
return true
end
local t2 = {"g", "h", "i"}
if tablesEqual(t, t2) then
print("t == t2")
end
-- Multi-dimensional tables
local twoD = {}
for i = 1, 3 do
twoD[i] = {}
for j = 1, i do
twoD[i][j] = i + j - 2
end
end
print("2d:", twoD)