【发布时间】:2017-07-17 16:36:24
【问题描述】:
一些背景:我在不同的 Lua 表中跟踪不同的硬件资源 - 对于每个硬件资源,我都有一个对应的 Lua 表。为了管理所有资源,我认为创建一个主表是有意义的,如果硬件资源是免费的,只需将对应的表实体设置为 nil。
下面的例子显示一个表格似乎链接了其中的另一个表格作为参考;但是,如果我将 nil 分配给表键,则只有键设置为 nil 而不是表本身,正如我真正希望的那样。 (参考最后 5 行的输出。)
local mainTable = {}
local subTable = {x = 123}
mainTable.subkey = subTable
print("The same value.")
print(mainTable.subkey.x)
print(subTable.x)
print("---")
print("The same value.")
mainTable.subkey.x = 456
print(mainTable.subkey.x)
print(subTable.x)
print("---")
print("Tables seem to have the same address.")
print(mainTable.subkey)
print(subTable)
print("---")
print("SubTable seems still to exist, even referance was set to nil")
mainTable.subkey = nil
print(mainTable.subkey)
print(subTable)
print(subTable.x)
输出:
The same value.
123
123
---
The same value.
456
456
---
Tables seem to have the same address.
table: 0x7f17a41596d0
table: 0x7f17a41596d0
---
SubTable seems still to exist, even referance was set to nil
nil
table: 0x7f4b48151710
456
是否可以在不设置 subTable = nil 和 mainTable.subkey = nil 的情况下从 subTable 中删除内部内容? (所以最后调用了 subTable 的 __gc 方法。)
【问题讨论】:
标签: lua pass-by-reference