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.我已经赋值vN[i]打印了,还是有10个。但是为什么我打印的时候t[0],我得到了nil

2.为什么__newindex不放循环元方法不起作用?(如果我把它t[0] = 10放在while循环外面,循环里面的元方法也会停止工作)

4

0 回答 0