Table (class)

From Moondust Wiki
Jump to navigation Jump to search

Tables store multiple pieces of data in a single variable and are defined by curvy brackets/braces: {}. All of the following are some of the common ways to create and manipulate tables.

local t = {}; --defines a table; this table is empty
local t = {5}; --defines a table; this table has one index

print(t[1]); --prints the first index of "t"; 5
local t = {"word", 5, 9}; --defines a table; this table has three indices

for _, v in ipairs(t) do print(v); end --prints all three indices of "t"
local t = {[3] = "word", ["another"] = 5, [4] = 9}; --defines a table; this table has three indices, but the indices are 3, "another", and 4; they are not consecutive

for _, v in pairs(t) do print(v); end --prints all three indices of "t", but this time in pairs must be used because the values are not consecutive in the table
local t = {}; --defines a table; this table is empty

for i = 1, 50 do t[i] = false; end --sets all of the indices of the table from 1 to 50 as false

There are many more functions of tables to explore which you can check out here: http://lua-users.org/wiki/TablesTutorial