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…
In general, you should call member functions by
:.In Lua, colon (
:) represents a call of a function, supplyingselfas the first parameter.Thus
Is roughly equal to
If you don’t specify A as in
A.foo(), the body of the function will try to referenceselfparameter, which hasn’t been filled neither explicitly nor implicitly.Note that if you call it from inside of the member function,
selfwill be already available:All of this information you’ll find in any good Lua book/tutorial.