|
Here resource management using scope like approach using for
statement:
in Lua 5.3
https://raw.githubusercontent.com/kov-serg/lua-aux/master/scope.lua
It enables to use auto and defer function for resource management.
It can be used for for coroutines:
https://raw.githubusercontent.com/kov-serg/lua-aux/master/proto-seq_fn.lua
Also a boilerplate code could be shorten by using macros.
for Lua 5.4 it can be modified to use to-be-closed vars:
https://raw.githubusercontent.com/kov-serg/lua-aux/master/auto_close.lua
But in this case you also have to call coroutine.close manually.
This approach hides to-be-closed variables from exposing to end
users.
To-be-close variable are good only as internal
mechanism, but not as general purpose.
And I believe it will cause a lot of bugs and problems in future if it will be widely applied.
1. There is a global table that maps coroutine --> stack-of-cleanup-tasks.These tasks are pushed/popped from the stack as the coroutine runs.2. Each cleanup task holds a reference to the cleanup function (I thinkthey can be weak if needed).3. In a coroutine, use the pcall+call method whenever a resource iscreated that needs to be cleaned up; the pcall wrapper will registerthe cleanup function in the global cleanup stack. If the pcall'd functionexits normally, the cleanup task will be popped and run.4. The coroutine could have a __gc method that does the cleanup, justby popping the cleanup tasks and running them.
This way, if the coroutine is suspended and its resources need to becleaned up, we either "close" it by running all of its cleanup routinesin reverse order, or we let it be GC'd, in which case the coroutine'sfinalizer will do the same.