So while looking through morph scripts I found this:
01 | function onTouched(hit) |
02 | if hit.Parent:findFirstChild( "Humanoid" ) ~ = nil and hit.Parent:findFirstChild( "Arm1" ) = = nil then |
03 | local g = script.Parent.Parent.Arm 1 :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.Part 0 = g.Middle |
10 | W.Part 1 = C [ i ] |
11 | local CJ = CFrame.new(g.Middle.Position) |
12 | local C 0 = g.Middle.CFrame:inverse()*CJ |
13 | local C 1 = C [ i ] .CFrame:inverse()*CJ |
14 | W.C 0 = C 0 |
15 | W.C 1 = C 1 |
I'd like to know what the # (eg #C) and the square brackets (eg C[i]) mean. Thanks in advance!
The Hashtag(#) symbol is used when referring to a quantity of something. i.e
1 | local aTable = { "Hello" , "Welcome" , "To" , "Scripting" , "Helpers!" } |
2 |
3 | for 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" |
5 | end |
1 | --Output: |
2 | --Hello |
3 | --Welcome |
4 | --To |
5 | --Scripting |
6 | --Helpers! |
#
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.
1 | workspace.Part |
2 | -- = |
3 | workspace [ "Part" ] |
Useful if then name of an object has spaces.
1 | --INCORRECT: |
2 | workspace.The Part |
3 |
4 | --CORRECT |
5 | workspace [ "The Part" ] |
Can also be used to get a value from a table via a number;
1 | local myTable = { "valA" , "valB" , "valC" } |
2 | print (myTable [ 2 ] ) --valB |
3 | print (myTable [ 3 ] ) --valC |
4 | print (myTable [ 1 ] ) --valA |
5 | print (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;
1 | local myTable = { "valA" , "valB" , "valC" } |
2 | for i = 1 , 3 do |
3 | print (myTable [ i ] ) |
4 | end |
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.
1 | local myTable = { "valA" , "valB" , "valC" } |
2 | local myString = "Hello!" |
3 |
4 | print (#myTable) |
5 | print (#myString) |