我正在尝试为穿入火炬设置一个玩具示例,但是从运行下面的代码时出现错误。我认为这可能只是我设置桌子的方式,但我不确定。
Threads = require 'threads'
Threads.serialization('threads.sharedserialize')
DataThreads = {}
DataThreads.__index = DataThreads
local result = {}
local unpack = unpack and unpack or table.unpack
function DataThreads.new(nThreads,opt_)
local self = {}
opt_ = opt_ or {}
self.threads = Threads(nThreads,
function()
print("background stuff")
end
)
self.threads:synchronize()
-- The below for loop is causing the error but the same :addjob() works later on
for i=1, nThreads do
self.threads:addjob(self._getFromThreads, self._pushResult)
end
return setmetatable(self,DataThreads)
end
function DataThreads._getFromThreads()
x,y = torch.uniform(),torch.uniform()
return x,y
end
function DataThreads._pushResult(...)
local res = {...}
if res == nil then
self.threads:synchronize()
end
result[1] = res
end
function DataThreads:getBatch()
self.threads:addjob(self._getFromThreads, self._pushResult)
self.threads:dojob()
local res = result[1]
result[1] = nil
if torch.type(res) == 'table' then
return unpack(res)
end
print(type(res))
return res
end
d = DataThreads.new(4)
错误在.new函数的
:addjob()
中发生。但是,稍后在:addjob()
函数中调用相同的:getBatch()
即可。设置元表之前,我是否不允许调用._getFromThreads(), ._getFromThreads()
函数?这是错误,我认为这意味着._getFromThreads()
没有返回任何内容;/home/msmith/torch/install/bin/luajit: ...e/msmith/torch/install/share/lua/5.1/threads/threads.lua:215: function callback expected
stack traceback:
[C]: in function 'assert'
...e/msmith/torch/install/share/lua/5.1/threads/threads.lua:215: in function 'addjob'
threads.lua:21: in function 'new'
threads.lua:54: in main chunk
最佳答案
当new
函数中的代码运行时,尚未设置元表,因此,当您使用self._getFromThreads
和self._pushResult
时,那里什么也没有,您又会得到nil
,这是无效的。
它在new
函数返回后起作用,因为此时已添加了元表,因此查找使用__index
元方法查找条目。
你可以做
local self = setmetatable({}, DataThreads)
立即设置元表,然后
return self
在末尾。
关于lua - 元表错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36020518/