OOP programming question

I am trying to use proper object oriented structure in my program, but running into an issue. I run into the issue when I try to call an object’s function from another function within the object using the “self” keyword. It is easier to give an example that explain:


function setup()
myRobot = Robot()

function draw()
    background(40, 40, 50)


Robot = class()

function Robot:init()
    self.name = "Robo"
    self.color = "grey"

function Robot:sayYourName()
    print("My name is: " .. self.name)

function Robot:sayYourColor()
    print("My color is: " .. self.color)

function Robot:giveInfo()
    self:sayYourName() --ERROR HERE
    self:sayYourColor() --AND HERE

I get this error: Attempt to index local “self” a nil value. Am I calling the function incorrectly? I have tried self.sayYourName() and self:sayYourName() with same results. Calling it like Robot:sayYourName() is inadequate because it does not have access to class variables.


Edit: I fixed a typo in the code, and replaced function call syntax with : instead of . and continue to receive same error.

Replace Robot:giveInfo() with myRobot:giveInfo() :wink:

Note that is should be self:sayYourName() and self:sayYourColor() in the giveInfo() function

Xavier, that was a typo on my part, using the class name rather than the object name. Also I changed the syntax to using a colon. The problem persists.

Hmm…everything looks to be fine, and in fact I just copied and pasted your code directly into Codea and it ran as intended with no errors.

Thanks. After reading your post I tried again, still fail. Then I killed Codea process and restarted and magically it works without change. Also, my other program that was failing which caused me to write the sample to ask for help now works. Maybe a little codea bug, I dunno. Will post again if it reoccurs.