Lua: Tables
Lua |
---|
Basics |
Intermediate |
Advanced |
|
XLua |
Add to this template |
Tables are the only real complex data structure provided in Lua. Tables are basically arrays, specifically associative arrays, associating a key with a corresponding value. Unlike most languages, Lua's tables start at 1 instead of 0. Lua tables can store every other data type, and even mixed types. The following is a valid table:
table1 = {
key = "test", -- defines 'key' and assigns 'test' to it
[3] = 5, -- assigns '5' to index 3
["what"] = true,
table2 = { }, -- creates a subtable in this table
testfunc = function(arg) return 10 end, -- this way of defining functions must be used in tables
not_here = nil, -- this value does not exist
[0] = "skipped", -- allowed but more or less ignored by default functions
}
Values in tables can be accessed in a few ways. One way is via dot syntax: table1.key will return test. Another is by specifying an integer index: table1[3] will return 5, not true, as 5 was explicitly stored in '[3]'. Strings can also used within square brackets: table1["what"] is exactly the same as table1.what. However, bracket syntax must be used instead of dot syntax in some cases; this is generally the case if you need an evaluated index, or if your index is not a valid identifier name (if it starts with a number or contains spaces, etc)
Functions inside tables can called in various ways; remember, they are variables, after all. table1.testfunc(arg) and table1["testfunc"](arg) are two valid ways to call a function. Functions are also able to use colon syntax, which effectively gives Lua OO capabilities. table1:testfunc(arg) is the same as table1.testfunc(table1, arg). Tables can be called like functions if they contain a __call metamethod.
Metatables are normal Lua tables that can be "attached" to other tables. They allow you to define otherwise undefined behavior: normally, adding two tables would result in an error. However, metatables allow you to define exactly how tables should be added, which would then make adding tables a valid operation. Tables can only have one metatable, but that metatable itself can have a metatable, and so on. Tables can even be their own metatables, which is useful for methods.