lua-users home
lua-l archive

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


On 10/19/07, Colin <share-lua@think42.com> wrote:
> Hallo,
>
> I am currently, for the first time, in the process of adding Lua scripting
> to a set of C++ applications and have reached the point of digging into
> error handling; after reading the following statement in the documentation:
>
> "You can also choose to use exceptions if you use C++"

What this sentence is referring to is the way Lua implements its error
handling functions.  Lua can use try/catch rather than setjmp/longjmp
for unwinding the C++ stack during error handling.  (In fact, this is
the default behavior; see luaconf.h.)

It helps not to view this as an attempt of Lua to provide a C++ API.
Lua's API is C through-and-through, and you'll get best results
thinking of it as such.  In general it's not very sporting to pass
function pointers to a pure C API when those functions might raise C++
exceptions.

Lua's use of the C++ exception mechanism does have a point, though.
The Lua functions pcall() and error() can cause lua_CFunctions in the
Lua call stack to be exited early as the stack is unwound.  The
interaction between setjmp/longjmp's and C++ destructors is left
explicitly undefined in the C++ spec.  By using try/catch instead, Lua
ensures that the destructors of your C++ locals get called if an error
causes an early exit.

But as far as I can gather looking at the code, that's all it's for.
As written, C++ exceptions cannot safely be thrown across a Lua
boundary [1].  For example, when built in C++, pcall actually gets
implemented using the scary catch(...).  No C++ exceptions at all will
ever make it through a pcall().

This actually feels typical and natural to me, but maybe I've spent
too much of my life writing C++ code to interface with C libraries.
Lua seems quite well behaved here.  You can rely on C++ idioms -- in
particular, exceptions and RAII -- in your C++-based implementations
of Lua fuctions, so long as you promise not to leak any of those
features to the underlying C library.

Greg F

[1] By that, I mean a C++ function calling a Lua function calling
another C++ function.