Lua: Tables
From Mario Fan Games Galaxy Wiki
Revision as of 01:13, 6 October 2009 by Draco Icebane (talk | contribs)
Lua |
---|
Basics |
Intermediate |
Advanced |
|
XLua |
Add to this template |
Tables compose Lua's only complex data structure. As such, they cannot be added together, unless supplied with a metatable.
Tables are associative arrays that begin the key index from 1. Values in a table may be of any other non-nil or mixed type, including methods / functions.
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.
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
}