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]印刷しましたが、それでも 10t[0]になりましたnil

__newindex2.ループに入れないとメタメソッドが動かないのはなぜですか? (ループの外に置くとt[0] = 10whileループ内のメタメソッドも動かなくなります)

4

0 に答える 0