用于表的__gc元方法的Lua 5.1解决方法 [英] Lua 5.1 workaround for __gc metamethod for tables

查看:450
本文介绍了用于表的__gc元方法的Lua 5.1解决方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前面临的问题是,对于Lua 5.1中的表,您不能对表使用__gc方法,因为它们是在Lua 5.2中实现的.但是,一旦lua表被收集,我想释放分配的本机资源.是否可以做一个变通办法,使我在Lua 5.2中为Lua 5.1提供__gc元方法的功能?

I'm currently facing the problem that you can't use the __gc method for tables in Lua 5.1, as they are implemented in Lua 5.2. However, I want to release allocated native resources once the lua table gets collected. Is it possible to make a workaround which gives me the functionality of __gc metamethod in Lua 5.2 for Lua 5.1?

推荐答案

在lua 5.1中,唯一与__gc元方法一起使用的lua值是userdata.自然,任何黑客或变通办法都必须以某种方式涉及userdata.通常,没有办法仅从lua端创建newuserdata,但是只有一个"隐藏"未记录的函数newproxy可以做到这一点.

In lua 5.1 the only lua values that work with __gc metamethod is userdata. Naturally any hack or workaround will have to involve userdata in someway. Normally there is no way to just create newuserdata from the lua side but there is one "hidden" undocumented function newproxy for doing just that.

newproxy采用可选的bool或userdata参数.如果传入true,则将获得带有新的元表的userdata.如果您传入另一个userdata,则将为新的用户数据分配与传入的用户数据相同的元表.

newproxy takes an optional bool or userdata parameter. If you pass in true then you get a userdata with a new metatable attached. If you pass in another userdata then the new userdata will be assigned the same metatable as the one passed in.

因此,现在您可以一起破解一个使__gc在表上工作的函数:

So now you can just hack together a function that'll make __gc work on tables:

function setmt__gc(t, mt)
  local prox = newproxy(true)
  getmetatable(prox).__gc = function() mt.__gc(t) end
  t[prox] = true
  return setmetatable(t, mt)
end

进行快速测试以确认其行为:

And a quick test to confirm the behavior:

iscollected = false
function gctest(self)
  iscollected = true
  print("cleaning up:", self)
end

test = setmt__gc({}, {__gc = gctest})
collectgarbage()
assert(not iscollected)

test = nil
collectgarbage()
assert(iscollected)

IDEOne演示

请注意,由于表上已正式支持__gc,因此lua 5.2+及更高版本不再具有newproxy.

Note that lua 5.2+ and later no longer have newproxy since __gc is officially supported on tables.

这篇关于用于表的__gc元方法的Lua 5.1解决方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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