3

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 Answers 2

7

Try this:

local ret, data = assert(pcall(the_function))
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.