Square braces (or brackets) are used for indexing.
That means asking for a value at an index. Indexing is how you use tables (which are usually used as either lists or dictionaries.
List Indexes/Indices
1 | local favorites = { 2 , 3 , 5 , 7 , 11 , 13 } |
Favorites is defined as a list in the above code. A list pairs locations (called keys or indices (plural of index) with elements (also called values).
The locations in favorites
are
The value at index 1
is 2
, the value at index 5
is 11
, etc.
To get the value at a given index, you use square braces:
The thing in the braces is just an expression, so we can use variables / do math:
3 | print ( favorites [ i + 2 ] ) |
Often this is done with a loop:
1 | for i = 1 , #favorites do |
The Dot
The .
is actually a fancy form of indexing. What you say a.b
, what you're really saying is a["b"]
, that is, "b"
, as a string, is an index to the object a
.
Indexing on ROBLOX Objects
For ROBLOX, that means game["Workspace"]
is the same thing as game.Workspace
.
This is helpful, since, for instance, character.Right Leg
isn't valid since there's a space in the name, but character["Right Leg"]
is okay because "Right Leg"
is just a string (and is allowed to contain a space).
Dictionaries
You can use any value as an index, except for nil
.