4

For example:

local my_table = { name = "my table" }
local my_table_mt = {}

function my_table_mt.__tostring(tbl)
    return "%s<%s>":format(tbl.name or "?", rawtostring(tbl))
end

Is something like this possible? I know the rawtostring method doesn't exist, but is there possibly a way to emulate this behavior, or to bypass it altogether?

Llamageddon
  • 3,306
  • 4
  • 25
  • 44

1 Answers1

3

There is only this kludge:

function rawtostring(t)
   local m=getmetatable(t)
   local f=m.__tostring
   m.__tostring=nil
   local s=tostring(t)
   m.__tostring=f
   return s
end
lhf
  • 70,581
  • 9
  • 108
  • 149
  • When dealing with code that uses `__metatable` to hide the true metatable, remember to use `debug.getmetatable` instead of the plain `getmetatable`. (If `__metatable` is in the way and you cannot use the `debug` module – e.g. in a restricted environment – you're out of luck.) – nobody Apr 08 '17 at 01:16
  • 1
    This code is totally safe in Lua. Lua is not thread-safe unless you build it you a global lock. Use different Lua states in different OS threads – lhf Apr 08 '17 at 01:58