如果我的userdata用作其他地方的密钥,如何处理Lua内存/引用?

时间:2014-06-24 04:16:40

标签: lua garbage-collection lua-table

我正在使用我的userdata索引一些表(让我们称之为Turret) - 存储一些相关的变量,如子弹和装甲。 我需要通过将其设置为零来管理Turret的生命周期,随后允许Lua将其GC化。我担心当我在别处使用它作为关键时,我对对象的记忆失去了所有控制权。

示例代码:

local turretStorage = {}

-- Bunch of turrets are created and added, lets look at the one below

local turret = load.newTurret(15) -- Create a Turret userdata
turretStorage[turret] = {}
turretStorage[turret].bullets = 100
turretStorage[turret].decal = "skulls.png"

-- Some time passes, we're done with the turret object
turretStorage[turret] = nil
turret = nil

我担心的是炮塔用户数据对turretStorage的索引。炮塔用户数据是否会得到GC' d?如果将turretStorage [..]设置为nil会删除关键参考 - 你能否告诉我支持文件?

我应该以某种方式在turretStorage表中找到密钥吗?如果是这样,我该怎么做?

如果该密钥被用作原始变量的参考而且无法删除,那么我会被困住并需要帮助或重构。

如果此示例中的密钥只是用户数据的内存位置用作唯一索引 - 那么我完全处于清晰状态;但是 - 已回答的问题将引用支持这一点;)

1 个答案:

答案 0 :(得分:2)

Lua中的对象仅被视为垃圾并且在Lua内部没有引用时标记为收集。使用值作为表中的键计为参考。

如果符合您的设计,请考虑使用weak tables