2016-05-22 12 views
2

Die Frage ist, aus dem torch5 Tutorial: http://torch5.sourceforge.net/manual/torch/index-8-1.htmlLua, Versuch, Indexfeld '__parent' (ein Null-Wert)

require "torch" 

-- for naming convenience 
do 
    --- creates a class "Foo" 
    local Foo = torch.class('Foo') 

    --- the initializer 
    function Foo:__init() 
    self.contents = "this is some text" 
    end 

    --- a method 
    function Foo:print() 
    print(self.contents) 
    end 

    --- another one 
    function Foo:bip() 
    print('bip') 
    end 

end 

--- now create an instance of Foo 
foo = Foo() 

--- try it out 
foo:print() 

--- create a class torch.Bar which 
--- inherits from Foo 
do 
    local Bar = torch.class('torch.Bar', 'Foo') 

    --- the initializer 
    function Bar:__init(stuff) 
    --- call the parent initializer on ourself 
    self.__parent.__init(self) 

    --- do some stuff 
    self.stuff = stuff 
    end 

    --- a new method 
    function Bar:boing() 
    print('boing!') 
    end 

    --- override parent's method 
    function Bar:print() 
    print(self.contents) 
    print(self.stuff) 
    end 
end 

--- create a new instance and use it 
bar = torch.Bar("ha ha!") 
bar:print() -- overrided method 
bar:boing() -- child method 
bar:bip() -- parent's method 

Nachdem dieses Skript ausgeführt wird, ich die Fehlermeldung bekam:

/Users/frankhe/torch/install/bin/luajit: test1.lua:39: attempt to index field '__parent' (a nil value) 

Hier ist das Bild der Details: enter image description here

Ich möchte wissen, warum dieser Fehler passiert ist.

Antwort

1

Verwendung:

local Bar, parent = torch.class('torch.Bar', 'Foo') 

Und:

function Bar:__init(stuff) 
    parent.__init(self) 

    self.stuff = stuff 
end 
+0

Dies löst das Problem. Könnten Sie mir jedoch sagen, warum 'self .__ eltering' nicht funktioniert? Vielen Dank! –

+1

So funktioniert das Klassensystem fackel7: siehe [Dokumentation] (https://github.com/torch/torch7/blob/master/doc/utility.md). Es gibt kein solches "__parent" -Feld. Stattdessen interagieren Sie direkt mit der Metatabelle der Elternklasse, die von ['torch.class'] (https://github.com/torch/torch7/blob/master/init.lua#L104-L107) zurückgegeben wird. – deltheil