lua-users home
lua-l archive

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


On Jun 9, 2011 2:32 PM, "Luiz Henrique de Figueiredo" <lhf@tecgraf.puc-rio.br> wrote:
>
> > IIRC the only time __tostring is called is by tostring(). I've been annoyed
> > several times that some other functions such as string.format and
> > lua_tostring don't call it. I'd consider it a bug, but the designers may
> > disagree...
>
> In Lua 5.2, __tostring will be called by string.format and there will be
> luaL_tolstring which respects __tostring.
>

That's good, but why a new C method, rather than making lua_tostring use it? It seems inconsistent with the rest of the API where you have to specify that you *don't* want to invoke metamethods. E.g. lua_gettable uses __index, and lua_rawget is available to bypass it - wouldn't it make more sense then to have a lua_rawtostring that does what lua_tostring does now?

My main concern is with adoption. Adding this functionality to a new method instead of the existing one means all existing C libraries will continue to not honour __tostring unless the author goes through and changes all lua_tostring calls to luaL_tolstring (assuming it's even still maintained). There's also likely to be a lot of programs that still just use lua_tostring because A) it's simpler[1] or B) it's the first thing they find when searching the manual.

For the most part, metamethods are "magic"; you don't have to think about them unless for some reason you want to *avoid* invoking them. This is one of my favourite features of Lua, as it makes it easy to create new objects that just work as expected. Having one of the metamethods not honoured by default seems counter-intuitive and awkward.

(As an example, I had made an app with a LuaGTK UI, which pulled all UI strings from a language file. Instead of e.g. :set_text("Clear"), you'd write :set_text(Text.UI.MainWindow.ClearButton). The actual value passed to set_text was not a string, but a table whose __tostring returned the appropriate string - this was so that if, say, Text.UI were missing from the language file, it could use some __index magic to fall back to a dummy string and log an error instead of crashing. I was disappointed to find my clever system didn't work quite as transparently as I'd hoped, since __tostring wouldn't get invoked when LuaGTK passed my object to lua_tostring...)

[1] assuming this is true. I haven't looked at the interface for luaL_tolstring, but the extra "l" tells me there's probably a length parameter involved?

--
Sent from my toaster.