Lua
Tables (Arrays and Maps)
Tables are Lua's only data structure — used as arrays and maps.
By EZ4Code Team
tablearraymap
Code
-- Array (1-indexed!)
local fruits = {"apple", "banana", "cherry"}
print(fruits[1]) -- "apple" (not fruits[0])
print(#fruits) -- 3 (length)
-- Map / dictionary
local person = {name = "Alice", age = 30, city = "NYC"}
print(person.name) -- "Alice"
print(person["age"]) -- 30
-- Mixed
local mixed = {10, 20, 30, name = "Bob", [100] = "indexed"}
print(mixed[1]) -- 10
print(mixed.name) -- "Bob"
print(mixed[100]) -- "indexed"
-- Iterate array
for i, v in ipairs(fruits) do
print(i, v)
end
-- Iterate map (no order guarantee)
for k, v in pairs(person) do
print(k, v)
end
-- Insert / remove
table.insert(fruits, "date")
table.remove(fruits, 1) -- removes "apple"Explanation
Tables are Lua's universal data structure — arrays, maps, objects, and modules all use tables. Arrays are 1-indexed (a common gotcha for newcomers). # returns array length but is undefined for sparse arrays. ipairs iterates array part in order; pairs iterates all keys (unordered). Use [n] for non-identifier keys.
More Lua Snippets
Metatables and OOP
Implement OOP and operator overloading via metatables.
Coroutines
Cooperative multitasking with coroutines.
Modules
Create reusable modules in Lua.
String Manipulation
Pattern matching and string functions in Lua.
File I/O
Read and write files in Lua.
OOP with Inheritance
Implement class inheritance using metatables.