lua-users home
lua-l archive

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


> I have another question on the semantics of to-be-closed variables,
> this time about error handling.  Consider the following example
> program
> 
> ---- tbc2.lua ----
> local function foo()
>     local t = {}
>     setmetatable(t, {__close = function() print(debug.getinfo(2).name) end})
>     local x <close> = t
>     error("stop")
> end
> 
> -- Added for good measure
> local function bar()
>     foo()
> end
> 
> pcall(bar)
> --- end ----
> 
> When I run this program with Lua 5.4.3, the output is
> 
> ----
> pcall
> ----
> 
> I would have expected "foo", because I thought that the close
> metamethod would be called "on the way out" of foo.  I haven't found
> an explanation for the actual behaviour in the docs.  I would like to
> know the reasons for this - are they tied to the implementation of
> to-be-closed variables, or is there a sound principle underlying this
> behaviour?

Both from the implementation and the specification point of views, the
error happened inside the call to function 'error' and it was caught
by pcall. All intermediate calls are discarded, there is no "way out"
of them. This semantics also has a slight advantage that both the stack
space and the memory used by these intermediate calls are free when
the close method runs.

-- Roberto