I've always seen this when scripting, or looking at others script. I mean, I know what for i, v in pairs do does. But every time I see this, I wonder, "What the does mean?" And I know, I have to include snippets, but, of MY script. Which I can not make without understanding the significance of this. for _, part in next,game.Selection:Get() do part.CFrame=part.CFrameCFrame.new(0,0,0)CFrame.Angles(math.rad(0),math.rad(0),math.rad(0)) end I saw this in the Wiki when searching for CFrame. And I need this answered, I recently started scripting, and I have a list full of things I need to learn. Not only that, but, I've also seen this for u, c in pairs do. Please answer this.
Pairs, next, and ipairs are all used to iterate through tables.
Pairs:
local tab = {"I", "like", "pie"} for i,v in pairs(tab) do print(i, "\t", v) --\t is an escape for tab. end
Output:
1 I 2 like 3 pie
Next:
local tab = {"I", "like", "pie"} for i,v in next, tab do print(i, "\t", v) end
Output:
1 I 2 like 3 pie
Another usage for next:
local tab = {"I", "like", "pie"} print(next(tab, 2))
The usage here is next(table, index)
Output:
3 pie
Ipairs:
local tab = {"I", "like", "pie"} for i,v in ipairs(tab) do print(i, "\t", v) --\t is an escape for tab. end
Output:
1 I 2 like 3 pie
The difference you say?
While pairs goes in no particular order, ipairs goes directly in the order the table is organized in and next goes directly to the next iterator.
Now for the example you have provided:
for _, part in next,game.Selection:Get() do
This is mostly used in building tools, when a few parts are being selected, the script can get all the parts selected into a table and do an action with them.
Example:
for _, part in next,game.Selection:Get() do part.CFrame = part.CFrame + Vector3.new(0, 5, 0) end
This makes the whole selection of parts go up 5 studs from where they were beforehand.
Further Reading:
The underscore ( ' _ ' ) is a valid variable name in Lua, and is typically used to represent return values you're not intending to use. In the example of the pairs iterator function, it returns the index and the value of the Table it is looping through. If you don't need the index, you use a '_' to represent that. If you don't need the value, you just ignore it and only supply a variable for the index.
As for the in next, Table do
bit, that is simply pulling the contents of the pairs function into the loop directly. It is functionally identical to in pairs(Table) do
.