Tables: Difference between revisions

From Legacy Roblox Wiki
Jump to navigationJump to search
>Mindraker
New
 
>Mindraker
New
(No difference)

Revision as of 11:17, 18 October 2008

Introduction

Table constructors are expressions that create and initialize tables. They are a distinctive feature of Lua and one of its most useful and versatile mechanisms.

The simplest constructor is the empty constructor, {}, which creates an empty table. Constructors also initialize arrays (called also sequences or lists). For instance, the statement

days = {"Sunday", "Monday", "Tuesday", "Wednesday",
            "Thursday", "Friday", "Saturday"}

will initialize days[1] with the string "Sunday" (the first element has always index 1, not 0), days[2] with "Monday", and so on:

days = {"Sunday", "Monday", "Tuesday", "Wednesday",
            "Thursday", "Friday", "Saturday"}
print(days[4])
Will result in:
Wednesday

For those that really want their arrays starting at 0, it is not difficult to write the following:

   days = {[0]="Sunday", "Monday", "Tuesday", "Wednesday",
           "Thursday", "Friday", "Saturday"}

Now, the first value, "Sunday", is at index 0. That zero does not affect the other fields, but "Monday" naturally goes to index 1, because it is the first list value in the constructor; the other values follow it. Despite this facility, I do not recommend the use of arrays starting at 0 in Lua. Remember that most functions assume that arrays start at index 1, and therefore will not handle such arrays correctly. You can always put a comma after the last entry. These trailing commas are optional, but are always valid:

   a = {[1]="red", [2]="green", [3]="blue",}

Such flexibility makes it easier to write programs that generate Lua tables, because they do not need to handle the last element as a special case. Finally, you can always use a semicolon instead of a comma in a constructor. We usually reserve semicolons to delimit different sections in a constructor, for instance to separate its list part from its record part:

   {x=10, y=45; "one", "two", "three"}

See Also

2.5 - Tables

3.6 - Table Constructors