Lua, attempt to index field '__parent' (a nil value)

匿名 (未验证) 提交于 2019-12-03 01:05:01

问题:

The question is from the torch5 tutorial: http://torch5.sourceforge.net/manual/torch/index-8-1.html

 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 

After running this script, I got the error message:

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

Here is the picture of details:

I want to know why this error happened.

回答1:

Use:

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

And:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!