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
--