I don't understand for _ = 1, total do loops

I was looking at an open-sourced script when I saw this code:

for _ = 1, numberOfParts do
	table.insert(parts, Instance.new("Part")) 

I don’t understand the “for _=1,numberofparts”, can someone explain it? I’ve seen for i = 1, 10 do kind of loop but I don’t get the _=1.

i is just a variable, you can change it to whatever you want, this is the same as:

for i = 1, numberOfParts do
	table.insert(parts, Instance.new("Part")) 

Btw, if for example local numberOfParts = 10 then, the loop would be:

for i = 1, 10 do
	table.insert(parts, Instance.new("Part")) 

You basically use _ = 1 if you don’t need the value that I stores. In your code, you don’t need to know the value of I so you don’t have to declare it. Note that I is a variable and you can change it to whatever you like

1 Like

All for loops need to declare a variable, but you might not always need it. The “_” indicates that the value is not going to be used thus making the code easier to read. It’s also often used in for … pairs/ipairs loops:

for _, part in ipairs(workspace.Model:GetChildren()) do

In this case, the “_” stands for the index of the part in the model. Since we only need the value (the actual part), we can use “_” as a name and only get the value. You don’t need to do it, but it’s recommended if you don’t use the variable, since anyone (including you) who later sees it can tell that it’s not getting used straight away.

besides what others have said
here is more information

Model isn’t a table, this wouldn’t work because it is an instance

you edited it nvm

1 Like

I like doing this in my code.

local children = function(model) return next, model:GetChildren() end


for i, v in children(workspace.Model) do
1 Like

oh yea that is fine, didn’t know because you had ipairs there

Are there any advantages to this though? As far as I know the pairs function uses the next function in Lua and ipairs is faster than pairs in Luau. Just seems a little redundant…

The difference here is that it automatically calls get children to shorten your code. I just like the look of it better but there are no efficiency advantages to it.
In fact, you could actually just integrate it into pairs:
local function pairs(t) if typeof(t)==“Instance” then return next, t: GetChildren () else return next, t end end

Universally speaking, when you see _ in lua or other languages, it means that whoever typed it doesn’t intend to be using that variable. For example:

local array = {...}
for _, v in pairs(array) do

In that piece of code, I didn’t use the idex variable, so I just replaced it with a _ for the sake of readability. It’s good practice to do that so when you pass your code to someone else, or even to yourself at times, you instantely know that variable isn’t going to be used and thus get a slightly better understanding of what you are going to deal with.