A luaT
class is basically either a Lua table or userdata with an
appropriate metatable. This appropriate metatable, that we call in
this section root metatable is created with luaT_newmetatable
.
The root metatable of a luaT
object has itself a metatable that we call
metaclass. The metaclass is the actual metatable containing all the
methods of the class. If the class inherit from another class, then the
metaclass will itself have a metatable corresponding to the parent metaclass:
the metaclasses are cascaded according to the class inheritance.
Multiple inheritance is not supported.
The root metatable of a luaT
object contains Lua
operators like __index
, __newindex
, __tostring
,
__add
(etc...). These operators will respectively look for __index__
, __newindex__
, __tostring__
,
__add__
(etc...) in the metaclass. If found, the corresponding function or value will be returned, else
a Lua error will be raised.
If one wants to provide __index__
or __newindex__
in the metaclass, these operators must follow a particular
scheme:
__index__
must either return a value and true
or return false
only. In the first case, it means
__index__
was able to handle the given argument (for e.g., the type was correct). The second case means
it was not able to do anything, so __index
in the root metatable can then try to see if the metaclass
contains the required value.
__newindex__
must either return true
or false
. As for __index__
, true
means it could handle
the argument and false
not. If not, the root metatable __newindex
will then raise an error if
the object was a userdata, or apply a rawset if the object was a Lua table.
Other metaclass operators like __tostring__
, __add__
, etc... do not have any particular constraint.
LUAT_API const void* luaT_newmetatable(lua_State *L, const char *tname, const char *parenttname, lua_CFunction constructor, lua_CFunction destructor, lua_CFunction factory);
LUAT_API void luaT_pushmetatable(lua_State *L, const void *id); LUAT_API void luaT_pushmetaclass(lua_State *L, const void *id); LUAT_API int luaT_getmetaclass(lua_State *L, int index);