Table

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].

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

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]

<nowiki>
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
</nowiki>

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:

<nowiki>
local tbl = { "one", "two", "three" }
print(tbl[2]) -- prints two
print(tbl[4]) -- prints nil
</nowiki>
gollark: Like this, can I write, should you it prefer.
gollark: The *grammar* is totally fine.
gollark: That's completely valid English.
gollark: All Culture ships have artificial gravitas, it's fine.
gollark: Well, yes, because it's dark as in "doesn't interact with light".

References

  1. Ierusalimschy, Roberto (March 2006). Programming in Lua. p. 32. ISBN 8590379825.
  2. Ierusalimschy, Roberto (March 2006). Programming in Lua. p. 33. ISBN 8590379825.
  3. Ierusalimschy, Roberto (March 2006). Programming in Lua. p. 34. ISBN 8590379825.
This article is issued from Computercraft. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.