Lua 关闭/程序执行结束回调 [英] Lua shutdown/End of the program execution callback

查看:54
本文介绍了Lua 关闭/程序执行结束回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 Lua 编写一个模块.在关闭 lua 解释器时,它必须运行清理例程,即使用户忘记隐式调用关闭例程.

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.

该模块主要是用 C 编写的.

The module is mostly written in C.

我应该使用 Lua C Api 中的哪个回调来检测程序执行的结束?我唯一的想法是在代表我的模块的表上使用 __gc 元方法.有什么想法吗?

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?

推荐答案

从 C 模块开始,最简单的事情就是创建一个带有 metatable 的完整 userdata使用 __gc 元方法.将其存储在模块环境中的一个字段中,以便在卸载模块之前不会被 GC 收集.

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.

根据手册,只有userdata 获取由收集器调用的 __gc 元方法,因此您不能使用表来保存模块的终结器.

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.

对于需要终结器的纯 Lua 编写的模块,您仍然需要有一个 userdata 来支撑它.可以使用不受支持和未记录但广为人知的函数 newproxy()创建一个否则为空的 userdata 带有用于此目的的元表.将其称为 newproxy(true) 以获取具有元表的一个,并使用 getmetatable() 检索元表,以便您可以添加 __gc元方法.

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.

这篇关于Lua 关闭/程序执行结束回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆