lua-users home
lua-l archive

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




2012/5/30 Tim Hill <drtimhill@gmail.com>

However, it seems to me that there is one hole in this clean model: the inability of a metatable to project a "type" into the Lua code space. Specifically, regardless of metatable, the value of type(someuserdata) is always "userdata". This means if I have several different userdata "types" in Lua code I cannot use them polymorphically without tracking their type manually (using, say, an ephemeron table). While tostring() can be used as a workaround (as it is for example with file handles) this seems too much like a hack to me; tostring() is supposed to return a value, not a type.


I have found that I could do it by storing the type of my objects in the metatable's __metatable field:

C:\>lua
Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> mt={__metatable="MyType"}
> o=setmetatable({},mt)
> =getmetatable(o)
MyType
>

This has the benefit of not changing the language, and also protects the metatable against unwanted access.

--
Benoit.