Reputation: 180
function iterator(N)
local i = i or 0 --Start from 0 so we can add it up later
if type(N) == "table" then --Check if N is a table or not, if not, error
print("Iterating through all values inside the table")
else
error("This is not an array")
end
return function()
setmetatable(N, {__newindex = --Print all values that has been assigned into N
function(t, k, v)
t[i] = v --Tried to assign v into N[i]
print(N[i]) --Still got 10 tho
print(k, v)--Print out the key(or index) that has been assigned into N
end })
i = i + 1 --Add 1 into i
return i , N[i] --Return index(or key) and the value of N
end
end
t = { 1, true}
AI = iterator(t)
t[0] = 10 --If i put this here, the metamethod won't work
while true do
Ind, N = AI()
print(N, Ind)
if t[0] == nil then --After metamethod ran, t[0] will be no longer nil(expected)
t[0] = 10 --Will print 0 10 two times(I expected 1)
print(t[0]) --Will print nil
end
if Ind >= #t then
break --Stop the iterator
end
end
1.I already assigned v
into N[i]
and printed it, still got 10. But why when I print t[0]
, I got nil
?
2.Why doesn't __newindex
metamethod work if I don't put t[0] = 10
in the while
loop?(if I put it outside the loop , the metamethod inside the loop will also stop working)
Upvotes: 0
Views: 44