Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

lua

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:

require "classlib"
Item = class("Item")

function Item:__init()
    self.interval = 1
end

function Item:getInterval()
    return self.interval
end

I'm calling this getter function like this:

dofile("../src/item.lua")

item = Item()

function test_item()
    assert_equal(1, item.getInterval())
end

What's the problem here?

Kind regards...

like image 551
zontragon Avatar asked Dec 28 '12 11:12

zontragon


2 Answers

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.

like image 159
Bartek Banachewicz Avatar answered Nov 18 '22 15:11

Bartek Banachewicz


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

like image 32
Alar Avatar answered Nov 18 '22 16:11

Alar