lua-users home
lua-l archive

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


Am 22.07.2013 13:58 schröbte John Hind:

This could also be usefully extended by a new '__type' metatable key. If
present, its value would be returned as the second return from type(). So
classes/types created from table or userdata type could easily be set up to
return an appropriate sub-type.

If you have type-inheritance and/or duck-typing, knowing the exact type isn't all that useful. I very much like Dirk Laurie's `has()` approach[1] (although I would choose a different implementation). One situation where having `__type` is nice is C code directly accessing a userdata's memory (-> `luaL_checkudata`). I currently have my own implementation of checkudata which uses the `__type` field to create error messages like

    bad argument #2 to '__add' (apr_oflags_t expected, got apr_fileattrs_t)

instead of

    bad argument #2 to '__add' (apr_oflags_t expected, got userdata)

This change would also be backwards compatible (unless someone parses those error messages). An alternative implementation could have `luaL_newmetatable` store a reverse mapping from metatable to type name for `luaL_checkudata` to use in error messages ...

  [1]: http://permalink.gmane.org/gmane.comp.lang.lua.general/99873

Philipp