Beginner question about variables.

I’ve been coding in codea since last November and there’s something I still don’t understand. In people’s projects and the example projects, all the variables have “self.” In front of them. What is the point of this and how do they work. Thanks.

You use self in classes, so the variable is special only to that class, makes sense?

@CodeaNoob
Important correction: you use self. in front of a variable name so as to make it unique to that INSTANCE of a class; you use that classes name and a “.” to make a variable unique to the class.

Example:

function setup()
    example1 = examp()
    example2 = examp()
end
function draw()
    example1:inc1()
    example2:inc2()
    output.clear()
    print("first examp instance: ")
    print("     -self.x="..example1:getx())
    print("     -examp.x="..example1:getclassx())
    print("second examp instance: ")
    print("     -self.x="..example2:getx())
    print("     -examp.x="..example2:getclassx())
end
examp = class()
examp.x = 0
function examp:init()
    self.x=0
end
function examp:inc1()
    self.x = self.x + 1
end
function examp:inc2()
    examp.x = examp.x + 2
end
function examp:getx()
    return self.x
end
function examp:getclassx()
    return examp.x
end

@Pirates19 - try reading posts 7 and 8 here

https://coolcodea.wordpress.com/2013/03/

Thanks for the help. The example and website you gave me helped me understand!

@Pirates19 - this may also help

https://coolcodea.wordpress.com/2014/10/01/169-why-tables-and-classes-are-so-useful/

@ignatz helpful link, I might start looking more into that site. However there’s one thing I don’t understand.

for i,r in pairs(rect) do --loop through
r.pos.y=r.pos.y+r.speed
–draw them
ellipse(r.pos.x,r.pos.y,r.pos.size)
end

The first line that mentions Pairs, what is “I” and how does codea know what “R” is?

(Sorry I don’t know how to annotate code)

@Pirates19 i and r are just variable names. They could be any name you want to give them. When used with the pairs keyword, i would be the index number of a table entry. r would be the table value at that entry. In other words, pairs is used to read the entries in a table, from start to finish. Each iteration returns the index number and the value.

@Pirates19 - you should read up on the Lua “for” command (Codea is based on the Lua programming language).

https://coolcodea.wordpress.com/2013/04/07/26-tables/

eg https://maurits.tv/data/garrysmod/wiki/wiki.garrysmod.com/indexbcba.html

http://codea.io/talk/discussion/6146/in-pairs