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

for i, v in pairs help?

Asked by
KAAK82 16
10 years ago

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

2 answers

Log in to vote
1
Answered by
Lacryma 548 Moderation Voter
10 years ago

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.

0
thnx, so k is model and v is a Child of model? KAAK82 16 — 10y
0
No k is the number the for loop is on and v is the value the for loop is on. Gamenew09 180 — 10y
Ad
Log in to vote
2
Answered by
Vividex 162
10 years ago

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

0
thnx, but sounds confusing... KAAK82 16 — 10y

Answer this question