lua-users home
lua-l archive

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


On Fri, Jan 17, 2014 at 3:38 PM, Andrew Starks <andrew.starks@trms.com> wrote:
>
>
>
> On Fri, Jan 17, 2014 at 6:43 AM, Justin Cormack
> <justin@specialbusservice.com> wrote:
>>
>> If I have a function
>>
>> function f() return nil, setmetatable({}, {__tostring = function()
>> return "error" end}) end
>>
>> and I use assert on it I annoyingly get
>> assert(f())
>> stdin:1: bad argument #2 to 'assert' (string expected, got table)
>>
>> Since 5.2, error() has been fixed to call __tostring it seems, so you
>> do not get "error object is not a string" messages.
>>
>> I find non string error types to be incredibly useful, you can give
>> them predicates so the user can find out more about the error in the
>> code, but this means casual use of assert is hard. I end up redefining
>> assert always, just to add the tostring call.
>>
>> Is there any reason for assert not to always call tostring?
>>
>> Justin
>>
>
> Justin, I agree with you on this. There are several things that I don't like
> about assert and error, which leads me to wrap them up in my own function.
> Something like:
>
> function assertx(cond, ...)
>    if cond then
>       return ...
>    else
>       return cond, tostring(select(1, ...)):format(select(2, ...))
>   end
>
> end
>
> ----
>
> I won't pretend to know the real answer, but I always assume it has to do
> with two things, in order:
>
> 1: Doing it the full-way (check the metatable, etc) adds complexity in
> functions that you want as fast as possible (assert fits that bill, error
> does not, as far as I can tell).
> 2: You can always wrap it and Lua is used in small / time critical systems,
> so the bar for 1 is sometimes rather low, given that there are a million
> ways to get around it (monkey patching, etc).

But the failure case of assert is not a fast path (obviously the
success case is), and it is basically similar to calling error() which
was fixed to use __tostring in metatables... So it looks more like an
oversight to me...

Justin