I saw this for loop in a script, how does it differ from the “for i,v in ipairs()” loop? Also what’s the hashtag for?
allies = {script.Parent.Name, "Figure","Civilian"}
for y,x in ipairs(allies) do
if x == v.Name then
break
elseif y == #allies then
target = torso
dist = findDistFromTorso(torso)
end
You can have any name, remember that the first one is the index while the second is the value. Ipairs only works for arrays and loops in an definite order and won’t work if something given in the table/array is nil. Pairs loop in definite order, and works for both array’s and tables.
local table1 = {1, 2, 3, 4, 5, nil}
for i, v in pairs(table1) do
print(v)
end
-->> 2
-->> 1
-->> 3
-->> 4
-->> nil
# finds the number of items in an array for example:
local array = {workspace.Part, workspace.Part1}
print(#array)
-->> 2
local myArray = {
1,
2,
3,
4
}
for i, v in ipairs(myArray) do
print(v, i)
end
-->> 1, 1
-->> 2, 2
-->> 3, 3
-->> 4, 4
The hashtag finds the length of a table, or how many things are in it. for key, value in ipairs(table) do will loop through an array (a table that has a specified order) and run the following code with key and value set to the current part of the table it’s on. For example,
local myTable = {4, 7, 1}
for i, v in ipairs(myTable) do
print(i, v)
end
--[[
output:
1 4; the first element of the table was 4
2 7; the second element was 7
3 1; & so on
]]
In that case, it runs the print for each item in the table. It gives it the index the number is located at (whether it’s the first element with 1, second element with 2, and so on) and the value of the number (4, 7, 1, etc.) You can store whatever you want in a table, so instead of 3, 7, and 1 you might have a bunch of strings like you do in your original post’s example.
Keep in mind key and value can be literally anything, like y and x (what you have) or someReallyAwfulVariableNameThatIsntHelpfulAtAll and cool. That just decides how you have to reference it from within the loop.
You can find more info on tables here that covers this in more depth:
ipairs is for arrays, and it respects the order the array is supposed to run in. It stops at the first gap in the table. pairs is for all kinds of tables, like dictionaries, and the order it runs in can be arbitrary.
Is there a general reason you might know as to why the author of this particular script decide to use “x,y” instead of the general “i,v” that everyone typically uses?
pairs and ipairs are examples of iterators factories. That means they return iterators. Iterators are functions that return the “next” element of a collection when you call them.
They’re not just used in for loops (although they usually are).
If you want to know more about iterators like pairs or ipairs, check out Programming in Lua : 7