lua-users home
lua-l archive

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




On Sun, May 10, 2020 at 2:47 AM DarkWiiPlayer <darkwiiplayer@hotmail.com> wrote:
Wouldn't it make sense to add a `__close` metamethod to coroutines then?
That seems to be exactly the kind of situation this feature is meant to
resolve in the first place.

That's easily added with this one liner:

debug.setmetatable(coroutine.running(), { __close = coroutine.close })

Note that for all types except tables and userdata objects there is only one metatable per type. I have no idea if there are any negative consequences as a result of doing this. I'm not so sure this is all that useful either, but it can be done.

My test code:
----------------------------------------------------------------------------------------------------

--  set metatable for ALL coroutines (just like strings coroutines share a single metatable)
debug.setmetatable(coroutine.running(), { __close = coroutine.close })


--  test code. Coroutine yields in an infinite loop
local function test()
    local on_close <close> = setmetatable({}, {
        __close = function()
            print("closing")
        end
    })
    local ctr = 1
    while true do
        coroutine.yield(ctr)
        ctr = ctr + 1
    end
end


do
    local co <close> = coroutine.create(test)
    for i = 1, 3 do
        local _, val = coroutine.resume(co)
        print(val)
    end
end


-- 

_______________________________________________
lua-l mailing list -- lua-l@lists.lua.org
To unsubscribe send an email to lua-l-leave@lists.lua.org