lua-users home
lua-l archive

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


Here's how I'd write an assert that saves both compilation and execution for last, and also avoids concatenations:

function compiled_assert(cond, --the condition to assert on
formatfs, --the code for a function to calculate the message if the assert fails
...) --the values that the function will need to compute its message

  if cond then --if the assert does not fail
    return cond, formatfs, ... --return all arguments (like assert())
  else error( --raise an error
    string.format( --with the formatting arguments
--returned from the execution of the function coded in the passed string
      --with the passed parameters
      assert(loadstring(formatfs))(...)
    ))
  end
end

So Marc's original example would be written as

compiled_assert( object:isValid(),
[[ ... = object
return "object %s is not valid", object:getName()]],
object)

In this way, all the call to assert sends, in addition to the initial condition calculation, are the initial values required to derive the final message, with no additional computation expended unless required.

Of course, this would really only be called for in situations where calculating the message for the assert is prohibitively expensive. In most cases, this complexity is not called for, and would just be premature optimization (trading a disproportionate amount of memory for CPU).

On Thu, 20 May 2010 09:53:26 -0700, Luiz Henrique de Figueiredo <lhf@tecgraf.puc-rio.br> wrote:

function assertc(condn,fun)
    if not condn then assert(false,fn()) end
end

Here's an assert on esteroids that can be used to avoid concatenations
for instance: