top | item 21146609

(no title)

yanex | 6 years ago

I suppose, just to close to-be-closed variables declared inside a sleeping coroutine.

discuss

order

i_feel_great|6 years ago

Why not let the function in the coroutine exit normally?

Maybe I should go read the docs. Killing a coroutine from the outside looks like poor design/bad idea.

ufo|6 years ago

Lua 5.4 has a new feature called to-be-closed variables. It is intended to allow for deterministic freeing of resources, even in the face of possible runtime exceptions. (Sort of like RAII in C++).

The canonical example is that you can mark a variable holding a file handle as to-be-closed and then as soon as you exit the variable's scope the file gets automatically closed (including if exit early due to break, return, or error).

But what is supposed to happen if you are inside a coroutine and pause the execution before reaching the end of the scope, and never resume again? If there are any to-be-closed variables their destructors will never run! Or they might only run after the containing coroutine gets garbage collected, which is not a timely solution. To cover this situation, Lua 5.4 introduced a new coroutine.close function that kills a paused coroutine and runs the destructors of any to-be-closed variables inside it, if there were any.