Table

From ComputerCraft
Jump to: navigation, search

A table is an implementation of a map.[1] That is, it associates several keys with values, both being of arbitrary type, with the exception of nil.[1][2] Should a table be indexed by a key that is not associated with a value, it will yield nil.[3] Vice-versa, assigning nil to a key will delete it.[3] Tables are Lua's only way of describing complex data structures, such as records and arrays.[2]

Syntax

A table literal is formatted as two corresponding swirly brackets {}, containing comma-separated key-value pairs formatted like [key] = value. To index a table, we use square brackets after the table expression containing an expression that evaluates to the key, such as tbl[1].

local tbl = { [1] = "one", [2] = "two", [3] = "three" }
print(tbl[2]) -- prints two
print(tbl[4]) -- prints nil

Records

In Lua, records are created by associating string keys with arbitrary-type values. For convenience, in the case of string keys only, the square brackets and quotation marks in the key-value pair definition may be omitted. Additionally, string-keyed tables may be indexed using the tbl.x syntax.[3]

local player = {
  x = 322,
  y = 64,
  z = 934
  health = 10
}

print(player.x) -- prints 322
print(player.y) -- prints 64
print(player.z) -- prints 934
print(player.health) -- prints 10
print(player.item) -- prints nil

Arrays

In Lua, arrays are represented as a table of values with consecutive numeric keys, starting at 1,[3] as seen above. To simplify the creation of arrays, the keys may be omitted altogether, which will instruct Lua to automatically assign ascending numeric indices to the values. Thus, the aforementioned example can be rewritten as such:

local tbl = { "one", "two", "three" }
print(tbl[2]) -- prints two
print(tbl[4]) -- prints nil

References

  1. 1.0 1.1 Ierusalimschy, Roberto (March 2006). Programming in Lua. p. 32. ISBN 8590379825. 
  2. 2.0 2.1 Ierusalimschy, Roberto (March 2006). Programming in Lua. p. 33. ISBN 8590379825. 
  3. 3.0 3.1 3.2 3.3 Ierusalimschy, Roberto (March 2006). Programming in Lua. p. 34. ISBN 8590379825.