I've seen people use brackets [] in lua, what do they mean?
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.
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
1
, 2
, 3
, 4
, 5
, and 6
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:
print( favorites[1] ) --> 2 print( favorites[6] ) --> 13
The thing in the braces is just an expression, so we can use variables / do math:
local i = 3 print( favorites[i] ) --> 5 print( favorites[ i + 2 ] ) --> 11
Often this is done with a loop:
for i = 1, #favorites do -- #favorites is the highest number you can index at -- ie, #favorties is the *length* of favorites print(favorites[i]) end --> 2 3 5 7 11 13 will be printed
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
.
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).
You can use any value as an index, except for nil
.
local obj = {} obj[1] = 2 obj["cat"] = dog obj[game] = workspace obj["game"] = 3 obj[false] = true print( obj[game] ) --> Workspace print( obj.game ) --> 3 print( obj["game"] ) --> 3 print( obj[false] ) --> true