0
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)

Vinni Marcon
  • 606
  • 1
  • 4
  • 18
BlaztOne
  • 180
  • 1
  • 10
  • you shouldn't assign a value to a table directly in it's `_newindex` it will create a`stackoverflow`. you should be using `rawset` – Nifim Aug 24 '20 at 15:56
  • I haven't learned about `rawset` yet, but thanks for the information anyways! – BlaztOne Aug 25 '20 at 02:51
  • 1
    I dont understand the intention of your code, but `t[0] = 10` only work if done before you call `AI()` because once `AI()` is called your metatable is applied to `t` and the `i` will be set to `1` so your `t[0] = 10` ends up being equivalent to `t[1] = 10` you may want to take a step back look at your code and ask if what you are doing makes sense, without more context i cant say if it does or not. – Nifim Aug 25 '20 at 04:51
  • Your answer is pretty clear, but you should add some commas to it. And I thought `t` is the original table? – BlaztOne Aug 27 '20 at 04:19
  • That would depend how you define "original". tables are by reference so when you do `iterator(t)` `t` and the `N` inside `iterator` reference the same table editing either will create changes in the other. – Nifim Aug 27 '20 at 13:04

0 Answers0