Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

for i, v in pairs help?

am a lil confused... plz tell me more about i v and pairs...

2 answers

✓ Accepted answer

You use pairs/ipairs to iterate/run through a table.

This would be a table: tab = {}

Now if we were to add something to the table, like so: tab = {"apple", "pear"}

Now, assume we do NOT know the values of tab and we need to output them or do a certain action with all the values. This is where pairs comes in handy.

tab = {"apple",  "pears"}

for k, v in pairs(tab) do print("Key: " .. k .. "Value: " .. v) end

Now let's do a more realistic example you are likely to use. Say you want to delete a few objects in a model. However, you only want to clear out the ones with the name apple. Pairs is widely used in this type of situations:

local model = Workspace.Tree:GetChildren() --GetChildren turns it to a table to iterate through

for k,v in pairs(model) do
if v.Name == "apple" then
v:Destroy()
end
end

Pairs separated it into a "key" and "value." In this case key is either the name or a number and value is the instance(model).

Finally, ipairs is identical to pairs except that it follows the values in the table in direct order.

2 comments

0

thnx, so k is model and v is a Child of model?

0

No k is the number the for loop is on and v is the value the for loop is on.

Returns three values: the next function, the table t, and nil, so that the construction

for k,v in pairs(t) do body end

will iterate over all key–value pairs of table t.

See function next for the caveats of modifying the table during its traversal.

t = {1,2,"a","d",c = 12, q = 20}
for i,v in pairs(t) do
	print(i,v)
end

Which would convert to after being ran to:

1 1 2 2 3 a 4 d c 12 q 20

Source: Pairs

1 comment

0

thnx, but sounds confusing...

This discussion is preserved as it was. New answers, comments, and votes are closed.