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 non-nil data type, and even mixed types. The following is a valid table:
example_table = {
[1] = "one", -- assigns "one" to first index, regular enumerated tables don't need the index explicitly stated
[0] = "can't touch this", -- index 0 is legal but Lua's table-based functions will ignore it
[5000] = "huge jump", -- Lua tables' array indexes are sparse, meaning this won't allocate memory for the unused 4999 indices
test = "variable key", -- variables may also be used within tables, accessed via 'table.var' or 'table["var"]'
["$"] = "string key", -- using an explicit string key allows characters that can't be used in variable names
[true] = false, -- other non-number and non-string datatypes can be used as keys (except nil)
subtable = { -- tables can be arbitrarily nested
subtable2 = { },
subtable3 = {
subtable4 = { },
},
},
func = function (arg) return arg end, -- functions/methods must be declared in this manner within tables
}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.
