lua-users home
lua-l archive

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

spir wrote:

How is the binding of a metatable to an object recorded? Is there an external table of (object:metatable) pairs?
Additional question: why isn't it set on the object itself (actually, it may be, but I couldn't access it)?

Well, metatables live up to their name in that they are meta-level entities, so isolation from the members of the table itself is warranted, but a metatable is actually set directly on the object (where "object" here is userdata or table). See lobject.h in the Lua sources, for example:

typedef struct Table {
  lu_byte flags;  /* 1<<p means tagmethod(p) is not present */
  lu_byte lsizenode;  /* log2 of size of `node' array */
  struct Table *metatable;a /* <== HERE */
  TValue *array;  /* array part */
  Node *node;
  Node *lastfree;  /* any free position is before this position */
  GCObject *gclist;
  int sizearray;  /* size of `array' array */
} Table;

Other types: string, number, function, cfunction and lightuserdata share metatables which are saved in the global_State struct...

Also is there another idiom for:
   setmetatable(t1, getmetatable(t0))

... so you can't really get around calling getmetatable and setmetatable functions (or Lua API equivalents), because the metatable lookup and setting is type dependent.

However, I seldom need to copy a metatable from one table to another, I prefer to keep them in variables.

Hope that helped.

Richard Hundt