lua-users home
lua-l archive

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

On Thu, Dec 24, 2020 at 5:28 PM DarkWiiPlayer wrote:
If you'd have to use first `type`, then `table.type` if it's a table, that
really defeats the purpose of metaprogramming: at that point you can
just as well expect others to read `getmetatable(something).__name`

You don't need to invoke type() before table.type().
Use the following check:
if table.type(v) == "MyClass" then

Reading "__name" manually is not a good solution for two reasons:
If v is a number or boolean then table.type(v) would return nil
(the same way as math.type() returns nil on non-numeric values)
But getmetatable(42).__name will raise an exception,
so you should check if metatable exists first.
If metatable is protected by the "__metatable" field,
you are unable to read its "__name" field directly.
But of course "__name" is not a secret field, there should be
some way to read it even for protected metatables.
And table.type() would be that way.