lua-users home
lua-l archive

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

The fundamental problem is that metamethods in Lua and operator overloading in C++ can change the meaning of + and - and hence potentially those operations can throw in either language.

If you know more about the types of the values involved, you can avoid that in particular cases. As written, the behavior of transfer_amount depends on the types of total1, total2, and amount. Given the full code, passing total1 and total2 as parameters was probably an error, but that still leaves the type of amount as a potential source of trouble.


On Oct 27, 2008, at 5:56 PM, David Manura wrote:

On Mon, Oct 27, 2008 at 8:18 AM, Roberto Ierusalimschy wrote:
Memory allocation errors may occur almost anywhere inside a Lua script.

On Mon, Oct 27, 2008 at 1:12 PM, Peter Cawley wrote:
...then they need to assume that every line may fail

In Lua must we then assume that every line may fail?  Here is a
function that transfers an amount between bank accounts:

 local total1 = 10
 local total2 = 10

 local function transfer_amount(total1, total2, amount)
   total1 = total1 - amount
   total2 = total2 + amount

Could the line "total1 = total1 - amount" execute but not the line
"total2 = total2 + amount"?  If so, we might pcall each statement and
add code to recover (total1 = total1 + amount), but what if the
recovery code fails?  In C/C++, those lines always succeed, at least
assuming no extraordinary condition (power failure, hardware failure,
OS crash, etc.).  The reason it succeeds is that all variables used
here, including temporaries, are allocated on the stack, and the stack
is preallocated.  Given restrictions on things like recursion, stack
requirements can be determined by static analysis[1].  In Lua,
however, the stack memory is allocated incrementally from the heap
(lua_Alloc) at unspecified times.