lua - 元表错误

标签 lua torch

我正在尝试为 torch 中的线程设置一个玩具示例,但运行下面的代码时出现错误。我认为这可能只是我设置 table 的方式,但我不确定。

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()处。但是稍后在 :getBatch() 函数中调用相同的 :addjob() 是有效的。在设置元表之前,我是否不允许调用 ._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._getFromThreadsself._pushResult 那里什么也没有,你得到 nil 返回,这是无效的。

它在new函数返回之后起作用,因为此时元表已被添加,因此查找使用__index元方法来查找条目已增加。

你可以做到

local self = setmetatable({}, DataThreads)

立即设置元表,然后

return self

最后。

关于lua - 元表错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36020518/

相关文章:

c - Lua的 "global"本地值存储在哪里?

docker - 使用 CUDA 在 docker 上运行 torch 表示未找到模块 'cutorch'

machine-learning - 二元标准的 Torch 混淆矩阵

python - 如何有效地乘以具有重复行的 torch 张量,而不将所有行存储在内存中或迭代?

c - 提取子数组

Lua 匹配字符串中字符后的所有内容

python - 关于 Tensorflow 和 PyTorch 中的自定义操作

torch - torch 中的列总和

function - 从lua中的函数args获取子表的索引

button - Corona SDK - "ShowOverlay"与 LetterBox 问题