Howdy, Stranger!

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

OOP programming question

edited May 2012 in Questions Posts: 179

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:

--MAIN function setup() myRobot = Robot() myRobot:giveInfo() end function draw() background(40, 40, 50) end --ROBOT CLASS Robot = class() function Robot:init() = "Robo" self.color = "grey" end function Robot:sayYourName() print("My name is: " .. end function Robot:sayYourColor() print("My color is: " .. self.color) end function Robot:giveInfo() self:sayYourName() --ERROR HERE self:sayYourColor() --AND HERE end

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.



  • edited May 2012 Posts: 196

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

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

  • Posts: 179

    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.

  • edited May 2012 Posts: 580

    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.

  • Posts: 179

    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.

Sign In or Register to comment.