Help understanding this

I don’t know what topic to put this under, was wondering whats the difference between these two, if any:

local ThisTable = {key = "value"}

for key, value in pairs(ThisTable) do
	print(key, value)
end

local i, value, key = pairs(ThisTable)

while true do
	local key, value = i(value, key)
	if key then
		
	else
		break
	end
	key = value
	print(key, value)
end
2 Likes

its scripting support iic since its a script

no difference, they just do the same thing, but harder, especially with the while loop, just use for loops.

1 Like

pairs returns the next iterator, the table, and the starting position for the iteration. There’s literally no difference except one will go until it errors. You may as well just do this:

for k, v in next, tbl, ThisTable, nil do
    print(key, value)
end

Source:
Lua 5.1 Docs
Lua 5.1 Reference Manual

4 Likes

The first example is concise and does not introduce unnecessary assignments.
Both do the same thing. The latter can/may lead to misleading results as key may not match the actual key from the table but will instead hold the value.

1 Like

I was thinking one would be more optimized, didn’t really expect them to be the same. Thank you!

1 Like

One is more optimised; the one that doesn’t use the while true iteration as it’s unneccessary. Use the first one if either of them.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.