lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


--- Tim Conkling <tconkling@brown.edu> wrote:
> Why doesn't the __index metamethod get called when I access
> table.var? The reference manual simply says '"index": the
indexing
> access table[key]' to describe when this function gets called.

Yeah, the manual's one-liner synopsis is misleading, but the
synposis is followed by clarifiying pseudocode (lua code actually):

if type(table) == "table" then
     local v = rawget(table, key)
     if v ~= nil then return v end
     ...

In other words, __index metamethod is only called if 'key' does not
exist in the table.

> I am trying to protect a table from being modified, and I thought
> the best way to do this would be through metatables

Well, since __index is called if 'key' doesn't exist, you could use
a stand-in for the table that has no keys:

local proxy_metatable = {}

proxy_metatable.__index = 
  function(proxy, key) 
    return rawget(getmetatable(proxy)[proxy], key)
  end

proxy_metatable.__newindex = 
  function(table, key, value) 
  end

function make_readonly(table)
  local proxy = {}
  proxy_metatable[proxy] = table
  setmetatable(proxy, proxy_metatable)
  return proxy
end


-----------------
-- Example usage:
-----------------

t = {}
t.a = "apple"
t.b = "ball"
t = make_readonly(t)

print(t.a, t.b)
t.a = "ardvaark"
t.b = "bat"
print(t.a, t.b)


__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free, easy-to-use web site design software
http://sitebuilder.yahoo.com