lua-users home
lua-l archive

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


Hi!

I've been thinking about dealing with 'assert ()' in case of complex
error message evaluation.
Say, we have something like this:

local function complex_call (a)
   if (math.sin (a*3 + 0.3) < 0.5) then
      return "Got no idea"
   else
      return "Damn, I don't know"
   end
end

assert (1 == 3, "Reactor response failure: "..complex_call (13))

It is known that error message is evaluated even if assertion succeeds.
It could be easy to replace it with lazy evaluation like this:

assert (1 == 3, function () return "Reactor response failure:
"..complex_call (13) end)

if assert () would accept both error message and error message
generating function.
So I suggest a patch like this for Lua 5.2.x and Lua 5.1.5:

@@ -333,8 +333,15 @@ static int luaB_dofile (lua_State *L) {

 static int luaB_assert (lua_State *L) {
   luaL_checkany(L, 1);
-  if (!lua_toboolean(L, 1))
+  if (!lua_toboolean(L, 1)) {
+    if (lua_isfunction(L, 2)) {
+      lua_checkstack(L, 1);
+      lua_pushvalue(L, 2);
+      lua_call(L, 0, 1);
+      lua_replace(L, 2);
+    }
     return luaL_error(L, "%s", luaL_optstring(L, 2, "assertion
failed!"));
+  }
   return lua_gettop(L);
 }

As an alternative additional version of assert () could be added.