Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

What is self?

What is self?

Comments

  • Posts: 3

    For example: self.x = x

  • dave1707dave1707 Mod
    Posts: 7,469

    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.

  • Posts: 3

    dave1707, Thank you

  • Posts: 69
  • edited June 2017 Posts: 121

    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

Sign In or Register to comment.