title: Read only iterable table in lua?
body: <p>I want to have a read only table in my Lua program. If ever a key is removed or a key is associated with a new value, an error must be thrown.</p>
  
  <pre><code>function readonly(table)
      local meta = { } -- metatable for proxy
      local proxy = { } -- this table is always empty
  
      meta.__index = table -- refer to table for lookups
      meta.__newindex = function(t, key, value)
          error("You cannot make any changes to this table!")
      end
  
      setmetatable(proxy, meta)
      return proxy -- user will use proxy instead
  end
  </code></pre>
  
  <p>It works great.</p>
  
  <pre><code>t = { }
  t["Apple"] = "Red"
  t[true] = "True!"
  t[51] = 29
  
  for k,v in pairs(t) do
      print(v)
  end
  
  t = readonly(t)
  t[51] = 30
  </code></pre>
  
  <p>Prints</p>
  
  <pre><code>Red
  True!
  29
  input:7: You cannot make any changes to this table!
  </code></pre>
  
  <h2><strong>Problem</strong></h2>
  
  <pre><code>for k, v in pairs(t) do
     print(v)
  end
  </code></pre>
  
  <p>Will print nothing under all circumstances now. That's because the <code>proxy</code> table will never have anything inside of it. <code>pairs</code> apparently never calls <code>index</code> and thus cannot retrieve anything from the actual table.</p>
  
  <p>What can I do to make this readonly table iterable?</p>
  
  <p>I'm on Lua 5.1 and have access to these metamethods: </p>
  
  <p><a href="https://www.lua.org/manual/5.1/manual.html" rel="nofollow noreferrer">Lua 5.1 Manual</a></p>