How to access nodes inside of for loop?

Let’s say I have a table with some nodes like

	self.social_media = {
		["discord"] = gui.get_node("discord"),
		["x"] = gui.get_node("x"),
		["telegram"] = gui.get_node("telegram")
	}

What’s the preferred way of looping over those nodes and accessing those nodes inside the loop?

Option 1

for key, value in pairs(self.social_media) do
    gui.set_scale(key, vmath.vector3(1.25, 1.25, 1))
end

Option 2

for key, value in pairs(self.social_media) do
    gui.set_scale(self.social_media[key], vmath.vector3(1.25, 1.25, 1))
end

Is there any difference in performance?

nodes are references, both work but option 1 is easier

Shouldn’t this be gui.set_scale(value, ...) ?

1 Like

Nope, it’s node then value. No idea why you’d put the value first

What I mean is that the key and value returned from pairs() would be of types string and node (or actually userdata), but in Option 1 in the original post the key was used.

self.social_media = {
	["discord"] = gui.get_node("discord"),
	["x"] = gui.get_node("x"),
	["telegram"] = gui.get_node("telegram")
}

-- Option 1 from original post
for key, value in pairs(self.social_media) do
	print(key) -- "discord", "x" or "telegram"
	gui.set_scale(key, vmath.vector3(1.25, 1.25, 1))
end

-- My suggestion
for key, value in pairs(self.social_media) do
	gui.set_scale(value, vmath.vector3(1.25, 1.25, 1))
end
2 Likes

I think you’re right because in my example “key” is a string while “value” would be the actual reference to the node.

So the question is if there is any difference between using self.social_media[key] and value inside the for loop and the answer is probably: No, but the second is easier to write (less characters).

Additionally it make sense to use for key, node instead of for key, value, right?

Yes, it clearer this way.

Not much of a difference performance wise no.

1 Like

We also recommend users to measure their test cases.
Use e.g. socket.gettime()before and after to measure your code snippet. That should give you an idea which solution is more performant.

1 Like

Oh yeah my bad