I would like to better understand how to use this function within scripting as I do not yet understand how to use it to its fullest.
✓ ANSWER ACCEPTED
Help with ipairs function?
1 answer
✓ Accepted answer
pairs and ipairs are the two default iterator functions. What this means is that they have a specific use: in a generic for loop.
ipairs iterates through an array, starting at index 1 and going up by one until it finds a value of nil.
Tables by default use array-indexing, so this will normally be what you want.
pairs, however, goes through every index-value pair once. The order, however, it not determinable until the loop is run at least once.
local table = workspace:GetChildren()
--This table looks something like:
--{workspace.Camera,workspace.Part,workspace.Terrain,workspace.Model}
table[#table + 2] = "This won't be reached by ipairs, because there is a value of `nil` at #table + 1"
table["Neither will this"] = "since it has a string key."
print('Ipairs loop:\n')
for i, v in ipairs(table) do
print(i) --Notice how these always appear in order.
print(v)
print('----')
end
print('\nPairs loop:\n')
for i, v in pairs(table) do
print(i) --Notice that now, the order is different. It's consistent, but in no general order.
print(v) --Also, they two that were missed are printed with `pairs`
print('----')
end
This discussion is preserved as it was. New answers, comments, and votes are closed.
