What is self?
For example: self.x = x
self is used in classes. It’s a variable description that is used for that class. I suggest that you find and read information about classes.
dave1707, Thank you
@Rusel04 Here is a good article on classes that helped me a lot:
http://codeatuts.blogspot.ch/2012/08/interlude-11-classes-in-lua-and-codea.html?m=1
The : operator is a shortcut when calling methods, using the variable as the first argument. self is automatically the name of the first argument when you write a function using the : operator…
function func.method(arg1) end --first argument is called arg1. Dot operator
function func:method() end --first argument is called self instead of arg1: colon operator
So if you write the method using dot operator, you can name the first argument whatever you like, it creates a local variable inside that block. But, If you use the colon operator, it’s going to be called self.
Note that if you write it using the dot operator, you can still call it with the colon operator. It doesn’t mean you access the first argument by saying self, it’s still whatever you named the arg in the dot operator. See below… t is the first argument. So even if i call the method using colon, i can still add everything up in t. Otherwise, that’d be really messy
(Methods are like when you make a table, and then you make a function inside that table)
points = {100,200,100,0,100,50}
function points.sum(t)
local sum = 0
for i, v in ipairs(t) do
sum = sum + v
end
return sum
end
function setup()
print ( points.sum(points) ) --550
print ( points:sum() ) -- also 550
end
There’s also metamethods and index and stuff, but i’m no good with the advanced stuff