lua-users home
lua-l archive

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



On 20 Jan 2009, at 22:07, Sam Roberts wrote:
One can pass anything to error, no?

No.

% lua
Lua 5.1.2  Copyright (C) 1994-2007 Lua.org, PUC-Rio
error({type="This"})
(error object is not a string)


My guess is this will probably change in Lua 5.2 with the new 'luaL_tolstring' (see http://lua-users.org/lists/lua-l/2008-02/msg00720.html) . Anyway, it can be easily "fixed" in the 'lua.c' with something like:

--- src/lua.original	2007-12-28 13:32:23.000000000 -0200
+++ src/lua.c	2009-01-20 22:41:45.000000000 -0200
@@ -74,8 +74,17 @@


 static int traceback (lua_State *L) {
-  if (!lua_isstring(L, 1))  /* 'message' not a string? */
-    return 1;  /* keep it intact */
+  if (!lua_isstring(L, 1)) {  /* 'message' not a string? */
+    lua_getfield(L, LUA_GLOBALSINDEX, "tostring");
+    if (lua_isfunction(L, -1)) {
+      lua_insert(L, -2);
+      lua_call(L, 1, 1);
+    }
+    else lua_pop(L, 1);  /* pop 'tostring' */
+    if (!lua_isstring(L, 1)) {  /* 'message' is still not a string? */
+      return 1;  /* keep it intact */
+    }
+  }
   lua_getfield(L, LUA_GLOBALSINDEX, "debug");
   if (!lua_istable(L, -1)) {
     lua_pop(L, 1);

With such change you could do:

Lua 5.1.3  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> Exception = setmetatable({
>> __tostring = function(self) return "Exception raised: "..self.message end
>> }, {
>>   __call = function(cls, obj) return setmetatable(obj, cls) end
>> })
>
> error(Exception{
>>   message = "some fancy error message",
>>   errorcode = 1234,
>>   stack = debug.traceback(),
>> })
Exception raised: some fancy error message
stack traceback:
	[C]: in function 'error'
	stdin:1: in main chunk
	[C]: ?

We use a similar approach in OiL to map CORBA exceptions. But users do have a lot of trouble when using it in the standard Lua console. For more info see:

  http://oil.luaforge.net/manual/corba/mapping.html#exception




--
Renato Maia
PhD student at PUC-Rio
__________________________
http://www.inf.puc-rio.br/~maia/