Llamageddon
Llamageddon

Reputation: 3526

Is it possible to bypass __tostring the way rawget/set bypasses __index/__newindex in Lua?

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?

Upvotes: 4

Views: 503

Answers (1)

lhf
lhf

Reputation: 72432

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

Upvotes: 3

Related Questions