lua-users home
lua-l archive

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

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.