User:OrenBochman/Lua Tables

From Meta, a Wikimedia project coordination wiki
Jump to navigation Jump to search

The table is Lua's primary data structure

Creating a table[edit]

numbers = {
   one = 1,
   two = 2,
   three = 3
}

Accessing a table element[edit]

return numbers.one -- returns 1


return numbers['one'] -- also returns 1

Numbered tables[edit]

africanFlatbreads = {
    'Aish Mehahra',
    'Injera',
    'Lahoh',
    'Ngome'
}

return africanFlatbreads[2] -- returns 'Injera'


Visiting each table element[edit]

  • pairs: key/value pairs in random order
for name, number in pairs(numbers) do
...
end
  • ipairs: Numeric keys in ascending order
for index, bread in ipairs(africanFlatbreads) do
...
end