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

What is "[ ]" operation/function used for in lua (easy question)?

Asked by 5 years ago

Looking through a lot of code I noticed that often there would be a variable and attached to it was another one with the help of []. Example: variable1[var2] and I have no clue what this function or operation does. Can someone please explain because i can't even look in the dev wiki since I do not know what it is called.

0
that means they are trying to access a table extremeparkrider 0 — 5y
0
oh, I see thanks! btw if you want some credit i'll accept your answer greenhamster1 180 — 5y
0
hahaha no need it is meant to be answered as quick as possible extremeparkrider 0 — 5y

2 answers

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

"Complex" or "compound" values in Lua are made with tables.

Tables are a group of key => value pairs. For example, you could have a table mapping fruits to their prices per pound:

local price_per_pound = {
    ["apple"] = 4.50,
    ["banana"] = 0.58,
    ["strawberry"] = 2.32,
}

A table associates a value with each key.

In the above table, "apple", "banana", and "strawberry" are the keys. The value associated with "apple" is 4.5. The value associated with "banana" is 0.58, and the value associated with "strawberry" is 2.32.

You can read the value associated with a key from a table using []:

local fruit = "banana"
print(price_per_pound[fruit]) --> 0.58

You can also associate a new value with a key using []:

-- Bananas got pricier!

price_per_pound["banana"] = 0.63

Lua provides a convenience syntax for []. If the key is a string that makes a valid variable name (e.g., "granny_smith" but not "granny smith", which has a space), instead of writing ["granny_smith"] you can write .granny_smith:

price_per_pound.granny_smith = 1.49
print(price_per_pound.granny_smith) --> 1.49
print(price_per_pound["granny_smith"]) -- 1.49

You can also drop the [" "] when defining a table with these keys:

 local price_per_pound = {
     banana = 0.63,
     granny_smith = 1.49,
 }

For example, if you write workspace.BlueTaslem to refer to my player's character, you could instead write workspace["BlueTaslem"].

When you're trying to refer to objects that have spaces in their names, you have to do this, since spaces mean the name isn't a valid variable name:

workspace.BlueTaslem["Left Arm"]
0
Why wasn't this accepted as the answer. I love how in depth it is and I even learned a ton from it! DatBroDo -6 — 5y
Ad
Log in to vote
0
Answered by
enes223 327 Moderation Voter
5 years ago

It's helping to find table values,functions,etc and its helping to use strings with space in functions like character["Right arm"]:remove(),etc.

2
this is misleading. Programical 653 — 5y
0
Misleading and uses :remove().. AizakkuZ 226 — 5y

Answer this question