Hey guys. I spent that last few months in C# and now coming back to Codea, I cant write Lua code to save my life.
It has a problem with self in
for i = 1, #self.ants do
in the draw function.
Edit: fixed the “:” in draw
Game = class()
function Game:init()
self.ants = {}
self.numberOfAnts = 5
self:CreateAnts()
end
function Game:draw()
print(#self.ants)
for i = 1, #self.ants do
self.ants[i]]:draw()
end
end
Yes, if you call a method with dot notation, the method won’t be able to access self, or rather it will look for self in the first argument that is passed to it.
instance:draw(args) is just a shorthand for myClass.draw(instance, args)
I’ve always wondered, why does Lua use the “:” rather than the “.”? I presume it is to make a distinction between being able to access self and not being able to, but if that is the case why not make the default “.” like in most other languages?
You can pass a different self, though you’re right that you probably wouldn’t want to. What it is very useful for, is for passing self to methods that are outside of the class (I think this is called meta-methods? You could call this a kind of multiple-inheritance ), or, in class-inheritance, invoking a method from the master class that the subclass has overwritten. Eg in mySubclass:init(args) you might call myMasterClass.init(self,args).
Self is just a word for the address of the current class instance.
You would pass a different self like this
A=someClass(). --<-- A holds the address of a table
B=someClass(). --<-- so does B
A:hits(B) --<-- this passes both tables to the hits function
A.hits(A,B) --<-- this does exactly the same thing
print(B.eye) --<--- "black"
function someClass:Hits(target)
self.hand="sore" --<--- self refers to the same table as A
target.eye="black"
end
PS the reason I knew what the error was, is that I made the same error many times when first learning Codea, so I remember it well
You can pass a different self, though you’re right that you probably wouldn’t want to.
But sometimes you want to fool the system and call a method on an instance of another class. This is how inheritance is implemented, for example:
Parent = class()
Child = class(Parent) -- inherit all methods from Parent
function Child:init() -- this overwrites the inherited initialisation function
Parent.init(self) -- so this is a way of calling the Parent init function on us
-- do some new stuff
end