Lua Tables

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9

Syntax

  • ipairs(numeric_table) -- Lua table with numeric indices iterator
  • pairs(input_table) -- generic Lua table iterator
  • key, value = next(input_table, input_key) -- Lua table value selector
  • table.insert(input_table, [position], value) -- insert specified value into the input table
  • removed_value = table.remove(input_table, [position]) -- pop last or remove value specified by position

Remarks

Tables are the only built-in data structure available in Lua. This is either elegant simplicity or confusing, depending on how you look at it.

A Lua table is a collection of key-value pairs where the keys are unique and neither the key nor the value is nil. As such, a Lua table can resemble a dictionary, hashmap or associative array from other languages. Many structural patterns can be built with tables: stacks, queues, sets, lists, graphs, etc. Finally, tables can be used to build classes in Lua and to create a module system.

Lua does not enforce any particular rules on how tables are used. The items contained in a table can be a mixture of Lua types. So, for example, one table could contain strings, functions, booleans, numbers, and even other tables as values or keys.

A Lua table with consecutive positive integer keys beginning with 1 is said to have a sequence. The key-value pairs with positive integer keys are the elements of the sequence. Other languages call this a 1-based array. Certain standard operations and functions only work on the sequence of a table and some have non-deterministic behavior when applied to a table without a sequence.

Setting a value in a table to nil removes it from the table. Iterators would no longer see the related key. When coding for a table with a sequence, it is important to avoid breaking the sequence; Only remove the last element or use a function, like the standard table.remove, that shifts elements down to close the gap.



Got any Lua Question?