Lua userdata资源释放

本文介绍了Lua中如何利用__gc元方法来处理资源释放问题,特别是在遍历目录并需要手动关闭句柄的场景下。通过创建一个结构体dir_info,定义dir函数和迭代器dir_iter,以及清理函数dir_clean,确保在lua中使用for in遍历目录时,能够正确关闭查询句柄,避免资源泄露。文章详细展示了相关函数的实现过程,并讨论了不同返回方式对泛型遍历的影响。
摘要由CSDN通过智能技术生成

首先来一段PIL中的说明:

Life is not always that easy. Sometimes, an object needs other resources besides raw memory, such as file descriptors, window handles, and the like. (Often these resources are just memory too, but managed by some other part of the system). In such cases, when the object becomes garbage and is collected, somehow those other resources must be released too. Several OO languages provide a specific mechanism (called finalizer or destructor) for that need. Lua provides finalizers in the form of the __gc metamethod. This metamethod only works for userdata values. When a userdatum is about to be collected and its metatable has a __gc field, Lua calls the value of this field (which should be a function), passing as an argument the userdatum itself. This function can then release any resource associated with that userdatum.

    假设现在我们需要写一个遍历目录的库,遍历文件基本流程是:

findFile   -> 打开一个编译句柄

nextFile  -> 遍历目录中的文件

closeFind -> 遍历完成

 

在lua使用遍历目录库:

for name in dir(path) do .... end

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值