Attempt to index local 'self' (a nil value)

前端 未结 3 1195
伪装坚强ぢ
伪装坚强ぢ 2021-01-11 09:25

I have a problem with classes. I got below error: Attempt to index local \'self\' (a nil value) When I call the getter method of below class. Item.lua file:

         


        
相关标签:
3条回答
  • 2021-01-11 09:57

    In general, you should call member functions by :.

    In Lua, colon (:) represents a call of a function, supplying self as the first parameter.

    Thus

    A:foo()
    

    Is roughly equal to

    A.foo(A)
    

    If you don't specify A as in A.foo(), the body of the function will try to reference self parameter, which hasn't been filled neither explicitly nor implicitly.

    Note that if you call it from inside of the member function, self will be already available:

    -- inside foo()
    -- these two are analogous
    self:bar()
    self.bar(self)
    

    All of this information you'll find in any good Lua book/tutorial.

    0 讨论(0)
  • 2021-01-11 10:09

    the obj:method is just syntactictal sugar for:

    definition:

    function obj:method(alpha) is equivalent to obj.method(self,alpha)

    execution:

    obj:method("somevalue") is equivalent to obj.method(obj,"somevalue") Regards

    0 讨论(0)
  • 2021-01-11 10:12

    Change:

    assert_equal(1, item.getInterval())
    

    to:

    assert_equal(1, item:getInterval())
    

    In Lua, it was some ridiculous for error reporting. From class point of view, the .getInterval() method should called with a self parameter, while the :getInterval() method is implicitly included the self parameter. And the syntax error should labeled in the called point, not the definition-body of getInterval().

    In traditional, while you miscalled a method, it was not the method's fault, but the caller.

    0 讨论(0)
提交回复
热议问题