What is this line of code doing?

Could someone explain what this code snippet is doing?

for k=1, #arr do local v = arr[k]
1 Like

I could explain it better with more code, but basically it is looping through a table, and making a variable called v that is equal to that value in the table.

for k = 1, #arr --for loop that increases until it reaches the number of values in the table
--then it sets a variable to the table[k]

It’s basically the same as:

for i, v in pairs(tablename) do
       
end
1 Like

Which one would you say is faster though?

1 Like

I would assume the one using in pairs, but I will have to do some testing. either way, the different is probably unnoticeable in tables under 1000 values.

1 Like

Yes, in pairs I would assume is faster because the other one needs an extra line to set the v variable.

No I dont think so because pairs is using a function call overhead and this one doesnt saving performance thus being faster

The one you wrote is faster than doing pairs. Check this thread:

I’ll test it. If we ran 2 coroutines at the same time we could test it.

Alright test it and get back to me with the results

1 Like

I have to go, here is the code I came up with. The problem is that one coroutine goes, then the other coroutine doesn’t start until the first one is finished. Maybe someone could fix my code so it works. The idea is to see which one stops printing first so that we know which loop is faster.

local testTable = {
	
}

for i = 1, 100 do
	table.insert(testTable, i)
end

wait(2)


local c = coroutine.wrap(function()
	for i, v in pairs (testTable) do
		print(v.." In pairs loop")
	end
end)

local a = coroutine.wrap(function()
	for k=1, #testTable do 
		local v = testTable[k]
		print(v.." Other loop")
	end
end)

a()
c()
1 Like

As said here, you should use numeric for loops when looping through a numeric-indexed array, but do note what he said.