如何在Torch中删除类变量?

我在理解 Torch 中类变量的工作方式时遇到了问题。

我做了以下操作:

mydata=torch.class('something')

我通过键入 who() 查看了用户变量,结果如下:

== User Variables ==
[_RESULT]        = table - size: 0
[mydata]         = table - size: 0
[something]      = table - size: 0

首先,我试图通过如下方式删除 mydata

mydata=nil

它起作用了。mydata 现在被释放了,可以被重新初始化为任何值。但当我尝试删除变量 something 时,输入

soemthing=nil

尽管变量 something 不再在 who() 中列出,但它似乎并不起作用。当我尝试:

mydata2=torch.class('something')

时,错误提示突然出现:

/data/torch/install/share/lua/5.1/torch/init.lua:65: something has been already assigned a factory
stack traceback:
        [C]: in function 'newmetatable'
        /data/torch/install/share/lua/5.1/torch/init.lua:65: in function 'class'
        [string "mydata2=torch.class('something')"]:1: in main chunk
        [C]: in function 'xpcall'
        /data/torch/install/share/lua/5.1/trepl/init.lua:648: in function 'repl'
        /data/torch/install/lib/luarocks/rocks/trepl/scm-1/bin/th:185: in main chunk
        [C]: at 0x00406670

有谁能告诉我背后的原因吗?

点赞
用户387870
用户387870

torch.class() 函数会将类的元表存储在 Lua 注册表中,参考 http://www.lua.org/pil/27.3.1.html 和 torch C 后端中的 luaT_lua_newmetatable() 函数。

为了卸载一个已存在的类,需要从 Lua 注册表中删除其条目。通过 debug.getregistry() 函数可以从 Lua 中访问注册表。

进行了注册表的删除后,你的示例便可以顺利运行:

mydata = torch.class('something')
mydata = nil
soemthing = nil

-- remove the global registration:
debug.getregistry()['something'] = nil

-- now it is possible to register the class again
mydata2 = torch.class('something')
2015-12-04 10:30:04