Howdy, Stranger!

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

Vars in a class / Array of a class

edited October 2012 in General Posts: 8


I have a question about objects. I get to the Methods via object:method. How can I reach the properties from outside, also with : ? Doesn't work. Or do I have to write a method/function for each var to give ist Out?

Can I have an Array of objects and use append array, object? How do I get the properties then?


Big greetings,



    Posts: 39

    Objects in lua/codea are actually tables. You can acces values in the object by the dot operator.
    The following examples all have the same effect:

    object.x = 10
    object ["x"] = 10
    object = { x = 10 }

    Methods are stored the same way. However, by using : instead of . you automatically pass the parameter "self" as its first argument.
    The following lines are equivalent:

    object.setpoint(self, x, y)
    Posts: 39

    You can have arrays of anything. arrays are also just tables in lua/codea.
    Arrays are implemented by tables with an integer as a key, instead of a name.
    Take care with the use of ipairs and pairs, and the #object command.

    Accessing values in an "array" is exactly the same as above.
    It's even possible to have arrays of objects holding other arrays and methods.

  • Thanks, I'll try...

  • edited October 2012 Posts: 8


    Could you Look at my constructor?


    RecordMove = class()

    function RecordMove:init(x,y,toX,toY)

        -- you can accept and set parameters here

        self.x = x

        self.y = y




    function RecordMove:draw()

        -- Codea does not automatically call this method



  • edited October 2012 Posts: 8

    And that's how I use it

                           -- store this move (to take it later back)



    Posts: 39

    That should work. It will add an instance of RecordMove to the movesList table at the first available spot in the array. Insert will search the table for the first integer index for which movesList[i] = nil. Great for stack implementations.

    you could shorten this by using

    table.insert ( movesList, RecordMove(inputX,inputY,i,j) )

    skipping the allocation to x1. This may be faster (didn't check).

    Acces the values by movesList[i].inputX etc..., but you probably figured that out already.

    edited October 2012 Posts: 39

    If RecordMove won't contain methods you could also use:

    table.insert (movesList, {x = inputX, y = inputY, toX = i, toY = j})

    sticking to a simple table implementation, not using the class RecordMove at all

  • Now it's working! Thanks a lot! I had other errors in the Lines, among others I thought movesList would start with 0....

Sign In or Register to comment.