3
votes

Depending if it errors are raised or not, pcall(function) may return:

Success: true and the return value[s] of the function.
Failure: false and the error.

In my case I'm calling a function to return a table, so in case of no errors I will get my data from the second return value, and in case of error I will print manage the error.

How can I do it with assert?

At first I wrote this:

local ret, data = pcall(the_function)
assert(ret, "Error: "..data)
-- use data from here on.

The problem is that the assert message is evaluated even in case of success, so when the call succeeds Lua complains about concatenating a string with a table.

This problem is due to the fact that I want to use assert and cite the error, but avoiding using something like if not ret then assert(false, "...") end.

2

2 Answers

7
votes

Try this:

local ret, data = assert(pcall(the_function))
4
votes

If you don't need to alter the error message from pcall lhf's suggestion is best.

Otherwise a solution is:

local ret, data = pcall( the_function )
assert( ret, type( data ) == 'string' and "Error: " .. data )

or this one, which is a cleaner approach:

local ret, data = pcall( the_function )
if not ret then error( "Error: " .. data ) end

this latter avoids completely to evaluate the error message expression if pcall doesn't give an error.