[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Second query about to-be-closed variables
- From: Roberto Ierusalimschy <roberto@...>
- Date: Tue, 18 Jan 2022 08:39:49 -0300
> 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