Howdy, Stranger!

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

Need help with tables!

in Questions Posts: 116

I made a class. I will define the objects of this class with its x and y coordinates. Also I want to put all objects in a table. Its difficult to explain, i will give an example. If i want to define an object, could i write myTable[x][y] = something? How can i reach this sort of "two layered" table? Maybe with myTable = {{}}? If you have questions, comment! Thanks for responses!

Comments

  • edited April 2015 Posts: 31

    Maybe something like this?
    This creates the objects in a table, then loops through the table drawing each object

    function setup()
        myTable = {}
        myTable[1] = myClass(100,100)
        myTable[2] = myClass(300,200)
    end
    
    function draw()
        background(40, 40, 50)
        for k,v in pairs(myTable) do
            v:draw()
        end
    end
    
    myClass = class()
    
    function myClass:init(x,y)
        self.x = x
        self.y = y
    end
    
    function myClass:draw()
        ellipse(self.x,self.y,50)
    end
    
  • Posts: 2,020

    Yes, the methods you describe do work for 2 layered tables. Presumably, this is for static objects (like a map grid in a platform game)? It's not going to work if you want the x and y coordinates to change. You'd have to define each layer of the inner table as an empty table before you populate it. E.g.

    --populate an x y grid with perlin noise values
    local seed = math.random(5000)
    local rough = 15
    map={}
    for x = 1,10 do
        map[x]={} --declare each column as a table
        for y = 1,10 do
            map[x][y]=noise(x/rough,y/rough,seed)
        end
    end
    
  • Posts: 116

    Bullseye! Thanks for fast and clear responses!
    P.S.: I figured the draw function out :P

Sign In or Register to comment.