lua-users home
lua-l archive

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


The definition of getbinhandler() in section 3.7 does not seem to
reflect what is actually implemented.  The current definition seems to
say that the lookup of an event in a metatable is an normal, not
rawget(), type of access and is thus subject to __index handling if
the event is not present.  The example below shows that this is not
the case.

It seems to me that the current behavior is less desirable than having
event processing subject to __index handling so metatables can be
chained to get inherited behavior.

Note in the example that I have defined __index in mt2 so it is
possible to retrieve methods such as sub() from the metatable of a
table.  Have you considered extending the behavior of the interpreter
so something like this is the default behavior for table accesses?
This might be useful for class-level variables.

Should "metatable" in section 3.7 be replaced by "getmetatable"?

Ed

======================================================================

mt1 = {
  add =
    function (self, a)
      print("add", self.v, a.v) 
      return self.v + a.v
    end
  ,
  __add =
    function (a, b)
      print("__add", a.v, b.v)
      return a.v + b.v
    end
}

mt2 = { 
  __parent = mt1
  ,
  __index = 
    function (table, key)
      local mt = getmetatable(table)
      return mt[key] or mt.__parent[key]
    end
  ,
  sub =
    function (self, a)
      print("sub", self.v, a.v)
      return self.v - a.v
    end
  ,
  __sub =
    function (a, b)
      print("__sub", a.v, b.v)
      return a.v - b.v
    end
}

a = { v = 1 } ; setmetatable(a, mt2)
b = { v = 2 } ; setmetatable(b, mt2)

print( a:sub(b) )
print( a - b    )
print( a:add(b) )
print( a + b    )

------------------------------------------------------

sub	1	2
-1
__sub	1	2
-1
add	1	2
3
lua: oo.lua:43: attempt to perform arithmetic on global `a' (a table value)
stack traceback:
	oo.lua:43: in main chunk
	[C]:[C]