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    	{0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,},
    	{0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,},
    	{"a" ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,"b" ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,},
    	{0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,"c" ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,},}
I would like to save the x and y of point "a", "b" and "c" and compare the y coordinate of "a" and "b" and the x coordinate of "b" and "c" and if they are the same to use them for a box2d rectangle, where the "a" x and y is the x and y of the rectangle and the difference of the x coordinate of "a" and "b" is the width and the difference in y from "b" to "c" as height.
I tried to atleast save "a", "b" and "c" to a table but i cant even do that, as the print() function returns nil.

Code: Select all

for y, xs in ipairs(grid ) do 
        for x, value in ipairs(xs) do 
            if value == "a" then  
                print("a is at x/y:" .. x .. "/" .. y)
                local a = {aX = x, aY = y}
                table.insert(aTable, a)
            end
            if value == "b" then 
                print("b is at x/y:" .. x .. "/" .. y)
                local b = {bX = x, bY = y}
                table.insert(bTable,  b)
            end
            if value == "c" then 
                print("c is at x/y:" .. x .. "/" .. y)
                local c = {cX = x, cY = y}
                table.insert(cTable,  a) 
            end
        end
    end
        print(aTable[1][1])
I really need some help as i cant wrap my head around this kind of stuff.
Thanks ^^

Re: Creating Geometry from a table of tables

Posted: Sat Sep 03, 2022 7:32 pm
by pgimeno
You're making local a, b, and c be tables that are not indexed by numbers, but by fields aX, aY, bX, bY, cX and cY. You insert them into aTable, bTable and cTable, so aTable[1] is a table with fields aX and aY, but when you try to print aTable[1][1], there is no element with numeric index 1.

What you need to print is:

Code: Select all

print(aTable[1].aX, aTable[1].aY)
By the way, notice that you have a copy-paste typo when inserting in cTable: table.insert(cTable, a) should be table.insert(cTable, c) instead.

Other than these two details, your code is fine.

Re: Creating Geometry from a table of tables

Posted: Sat Sep 03, 2022 8:46 pm
by NoreoAlles
pgimeno wrote: Sat Sep 03, 2022 7:32 pm You're making local a, b, and c be tables that are not indexed by numbers, but by fields aX, aY, bX, bY, cX and cY. You insert them into aTable, bTable and cTable, so aTable[1] is a table with fields aX and aY, but when you try to print aTable[1][1], there is no element with numeric index 1.

What you need to print is:

Code: Select all

print(aTable[1].aX, aTable[1].aY)
Thanks :awesome: