lua-users home
lua-l archive

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


On Wednesday, November 19, 2014 08:25:47 PM Rena wrote:
> This is something I've brought up before (and seems to fit in with the
> current int vs float discussion as well). In a lot of cases it's easy
> and convenient to use Duck Typing in Lua. You don't check types, you
> check capabilities (can this be called? does it have an "animate"
> method?) or you just assume the objects are compatible and let an
> error be thrown if not.

And if you don't like the error messages Lua give you, or want to recover 
gracefully from a type error, then you have pcall. In fact, pcall is a sort of 
"iscallable" function as it will fail gracefully if the first argument isn't a 
function.

However, this has the side-effect that an error in the function will not 
bubble past the pcall. So you won't know the difference between:

function call_or_index(something, param)
    local success, result = pcall(something, param)
    if not success then result = something[param] end
    return result
end

notcallable = call_or_index(123, "this is not a function")
errorinfunction = call_or_index(function(param)
    return param["this is indexing a number"]
  end, 123)

The second will fail by saying "attempt to index a function" in the 
call_or_index function. But that's not where the error actually is. And it 
would be worse if I put the `something[param]` in a pcall in order to handle 
that error myself.

Lua errors aren't fine-grained enough for this. That's why you want to check 
the preconditions, and thus the desire for a iscallable function. Or, 
alternatively, a trycall (or "tcall"?) that attempts to call a function and 
returns the results if successful, or `false` if it's not callable. Just like 
pcall but without the protected context.

-- 
tom <telliamed@whoopdedo.org>