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

What are square brackets ([]) and hashtags (#) used for?

Asked by 10 years ago

So while looking through morph scripts I found this:

01function onTouched(hit)
02    if hit.Parent:findFirstChild("Humanoid") ~= nil and hit.Parent:findFirstChild("Arm1") == nil then
03        local g = script.Parent.Parent.Arm1:clone()
04        g.Parent = hit.Parent
05        local C = g:GetChildren()
06        for i=1, #C do
07            if C[i].className == "Part" then
08                local W = Instance.new("Weld")
09                W.Part0 = g.Middle
10                W.Part1 = C[i]
11                local CJ = CFrame.new(g.Middle.Position)
12                local C0 = g.Middle.CFrame:inverse()*CJ
13                local C1 = C[i].CFrame:inverse()*CJ
14                W.C0 = C0
15                W.C1 = C1
View all 37 lines...

I'd like to know what the # (eg #C) and the square brackets (eg C[i]) mean. Thanks in advance!

2 answers

Log in to vote
1
Answered by
Mr_Octree 101
10 years ago

The Hashtag(#) symbol is used when referring to a quantity of something. i.e

1local aTable = {"Hello","Welcome","To","Scripting","Helpers!"}
2 
3for i = 1,#aTable do --The for loop executes depending on the number of items in aTable
4    print(aTable[i]) --This prints the string that corresponds with the item number; i.e. print(aTable[2]) would print, "Welcome"
5end
1--Output:
2--Hello
3--Welcome
4--To
5--Scripting
6--Helpers!
Ad
Log in to vote
1
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
10 years ago

# is used to find the length of a list or a string. It returns a number.

[] are used to either search for a child via a string, or search a list via a number. It returns the object or value.


Brackets:

Just like a dot, but you can use a string, i.e.

1workspace.Part
2-- =
3workspace["Part"]

Useful if then name of an object has spaces.

1--INCORRECT:
2workspace.The Part
3 
4--CORRECT
5workspace["The Part"]

Can also be used to get a value from a table via a number;

1local myTable = {"valA", "valB", "valC"}
2print(myTable[2]) --valB
3print(myTable[3]) --valC
4print(myTable[1]) --valA
5print(myTable[math.random(1,3)]) --random

If you have a variable for a number, and that variable is changing, you can "loop through" the list;

1local myTable = {"valA", "valB", "valC"}
2for i = 1,3 do
3    print(myTable[i])
4end

The GetChildren() method returns a table of all the children of an object, so it works the same way.


Number sign:

It's best not to think of it as a hashtag or the pounds symbol, because in Lua it is used as a number sign. When placed before a list, it return the number of that list. It can also be used for strings; it will return the number of characters.

1local myTable = {"valA", "valB", "valC"}
2local myString = "Hello!"
3 
4print(#myTable)
5print(#myString)

Answer this question