lua-users home
lua-l archive

Re: tag method for dostring?

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


> I was perusing the lua 3.0 documentation, and I was looking for a tag
> method that could be overridden for tostring() and tonumber(). Do
> these exist? If not, they might be a useful addition to the language
> so that userdatas could be more easily debugged.
What you can do is to override the functions "tostring" and "tonumber",
so they can handle your special cases. A simple way to do that is as
follows:
Howtoshow = {} -- keep functions to show selected tags
old_tostring = tostring
function tostring (o) -- redefine 'tostring'
 local f = Howtoshow[tag(o)]
 if f then return f(o)
 else return old_tostring(o)
 end
end
-- supose 'tt' is a new tag, and 'foo' is
-- the function you want to use to convert
-- such objects to strings:
Howtoshow[tt] = foo
----
Notice: in Lua 3.1, you could write the above
function as (there is no need of 'old_tostring'):
function tostring (o)
 local f = Howtoshow[tag(o)]
 if f then return f(o)
 else return %tostring(o)
 end
end
-- Roberto

AltStyle によって変換されたページ (->オリジナル) /