Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
3

What are brackets in lua?

Asked by
yoshiegg6 176
9 years ago

I've seen people use brackets [] in lua, what do they mean?

1 answer

Log in to vote
4
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

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

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 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.

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
0
I have a crafting system in my game, and I have a dictionary titled "recipes," and each index is a table containing the items needed to craft the index. Just thought I'd share that. yumtaste 476 — 9y
0
Thank you for explaining that for me. yoshiegg6 176 — 9y
Ad

Answer this question