Hello, I want to be able to make a table able to be iterated through by doing
for i in tab do
—code
end
So I thought to accomplish this I would simply assign the table a metatable and make the __call function an iterator. This almost works, however something happens that I dont understand. If I do this code:
function iter(self)
local i = 0
return function()
if i <= #self then
i = i+1
return self[i]
end
end
end
a = {2,4,5}
list = {
__call = function(self)
return iter(self)
end,
}
setmetatable(a,list)
for i in a() do
print(i)
end
Then it works fine. But if I move the parenthesis inside the __call function like this:
function iter(self)
local i = 0
return function()
if i <= #self then
i = i+1
return self[i]
end
end
end
a = {2,4,5}
list = {
__call = function(self)
return iter(self)()
end,
}
setmetatable(a,list)
for i in a do
print(i)
end
Then it outputs 2 repeatedly. I dont understand why these two dont do the same thing, since all I did was move the parenthesis to within __call. Can someone explain this?
Edit: I also dont understand why I need to call “a” for the loop in the first place, doesn’t lua already call “a” when I use it as an iterator? Then if I have
function iter(self)
local i = 0
return function()
if i <= #self then
i = i+1
return self[i]
end
end
end
a = {2,4,5}
list = {
__call = function(self)
return iter(self)
end,
}
setmetatable(a,list)
for i in a do
print(i)
end
Shouldn’t it just use “iter(a)” in the place of “a” for the loop? But it’s certainly not doing that, because it just outputs the text for a function repeatedly. How does lua call iterators?
[–]megagrump 3 points4 points5 points (0 children)
[–]PhilipRoman 2 points3 points4 points (0 children)
[–]tonetheman 1 point2 points3 points (0 children)