lua-users home
lua-l archive

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


On Fri, Jul 31, 2020 at 2:20 PM Egor Skriptunoff
<egor.skriptunoff@gmail.com> wrote:
> local thread = coroutine.wrap(function()
>    local please <close> = setmetatable({}, {__close = function()
>       print"coroutine toclose"
>    end})
>    print"coroutine yields"
>    coroutine.yield()
>    print"coroutine ends"
> end)
> thread()
> print"program exit"
>
> I don't see "coroutine toclose" printed.
> The Lua manual says we should invoke coroutine.close().
> But we can't  :-)

Yes, I think you are right: coroutine.wrap is not usable for now.
However, I would avoid the "Do something at exit" policy. I would
prefer to change the coroutine.wrap implementation to something
__gc/__close -aware [1].

For create/resume instead, I am not fully sure that any automatism is
a good idea. Maybe a lower level design is more flexible: if you
really need, you can use them to build wrappers with automatic
__gc/__close calls [1].

--

[1] Something like:

local function cowrap(f)
  local thread = coroutine.create(f)
  local closed = false
  local function doclose()
    if not closed then
      coroutine.close(thread)
      closed = true
    end
  end
  return setmetatable({},{
    __call = function(_,...)
      return coroutine.resume(thread,...)
    end,
    __close=doclose,
    __gc=doclose,
  })
end