lua-users home
lua-l archive

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

One of the "common" problems with functional languages (I know that Lua is
not a such thing, but it can easily be used as one) is the problem with
handling return values and errors at the same time.

The problem is that if a function is doing good I would like to return the
result but if it goes bad I would like to know why? But combining return
values and error values is a mess (When is it a error and when is it a
value) .. Adding Lua possibility to return any number of return-values makes
this almost impossible to do consistent across multiple libraries..

My suggestion is to add information to the state that will hold information
on the last error. This information will automaticly be  cleared in the
callC function (in LDO.C) so the errors are not carried over from one C to
the next C function.

So in Lua a plain C function could look like this:

void OpenDatabase()
  char *DatabaseName = luaL_check_string(1);
  if (Able to open database)
    lua_state->LastError = GetLastErrorFromDatabaseEngine();

In that way the Lua programming could look like:

db = OpenDatabase("customer_information")
if db == nil then
  print("Error "..GetStateError())

The modification to the state would be to add:

unsigned long   LastError;
unsigned long   LastError2; // Used for the GetStateError function

The modification to callC would be

if (lua_state->LastError != 0)
  lua_state->LastError2 = lua_state->LastError;
  lua_state->LastError = 0;
just before the (*F)() function call.

then add a extra function the api

void GetStateError()

This way I'm able to handle error the same way across all my libraries
(gui,database,network etc)...

Any comments?