Lua: Tables
From Mario Fan Games Galaxy Wiki
Lua |
---|
Basics |
Intermediate |
Advanced |
|
XLua |
Add to this template |
Tables compose Lua's only complex data structure. As such, they are used to represent basic datatypes such as arrays and dictionaries, and more complicated ones such as objects and trees. They can freely include both numeric and non-numeric keys, the former begin at 1, like strings.
When a variable is assigned to a table, it may be accessed by the following terms:
- table.varname and table["varname"], where varname is the name of the assigned variable. The latter must be used if the variable name contains otherwise invalid characters, for syntax parsing purposes.
- table[x], where x is the key's index.
- table.function(), table.["function"](), or table:function(), to call a function or method (which is simply another type of variable.) Any values added into parenthesis are parameters.
- Tables themselves may be called as a function if they contain the metamethod __call.
Behaviors such as addition are not implemented for tables, but metatables allow defining this, along with many other behaviors.
Example code
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 table-based functions will ignore it
[5000] = "huge jump", -- Won't allocate memory for unused 4999 indices
var = "variable key", -- Variables are accessed with '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 may be nested freely
subtable2 = { },
subtable3 = {
subtable4 = { },
},
},
func = function (arg) return arg end, -- functions/methods must be declared in this manner within tables
}