Lua shutdown/End of the program execution callback

落爺英雄遲暮 提交于 2019-12-01 21:06:29

问题


I am writing a module for Lua. On closing the lua interpreter it must run clean up routines even if user forgets to call shutdown routine implicitly.

The module is mostly written in C.

What callback in Lua C Api should I use to detect end of program execution? The only idea I have come with is using __gc metamethod on table representing my module. Any ideas?


回答1:


From a C module, the simple thing to do is to create a full userdata with a metatable with a __gc metamethod. Store it in a field in the module's environment so it isn't collected by the GC until the module is unloaded.

According to the manual, only userdata get their __gc metamethod called by the collector, so you can't use a table to hold the module's finalizer.

For a module written in pure Lua that needs a finalizer, you still need to have a userdata to hold it up. The unsupported and undocumented but widely known function newproxy() can be used to create an otherwise empty userdata with a metatable to use for this purpose. Call it as newproxy(true) to get one with a metatable, and use getmetatable() to retrieve the metatable so you can add the __gc metamethod to it.



来源:https://stackoverflow.com/questions/3912296/lua-shutdown-end-of-the-program-execution-callback

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!