Use assert with pcall in Lua

lua

Solution

Try this:

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

Problem

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`.

Original source