Question

I'm a beginner Lua user, I attempt to create something in Lua by using Love2D libraries.

In the loading function I create a table and upload it with elements (which are numbers) for use it later as a multidimensional array.

function love.load()

    Maximum_X = 32      
    Maximum_Y = 16

    Start_X = 64
    Start_Y = 32

    MapTable = {}                           -- empty table

    for i=1,Maximum_X*Maximum_Y do          -- uploading table
        table.insert(MapTable, 2)
  end


end

Then I make a function that takes changes in the table. Because I'm just experimenting with tables, there's only one changed value. At least, I thought.

function KatamoriGen()

    MapTable[4] = 3     

end


function love.update(dt)

KatamoriGen()

end

After that, I print the elements of the table in a matrix with 32 coloumns and 16 rows. I see here that not only the 4th element of 1st row is changed, but also the 2nd element of 2nd row and 1st element of 4th row becomes 3.

It obviously means that Table[posX*posY] doesn't work neither since the result of the multiplication is a number like 4 and the operation would change every elements where

X coordinate + Y coordinate = posX*posY

is true. In the example code, the right side of this equation was 4.

A small question: why is it happening?

The main question is: how can I identify elements of MapTable exactly? How can I implement X and Y dimensions to Lua tables? to use them as two-dimensional arrays? Maybe table of tables?

EDIT: this is the drawing function:

function love.draw()    

for j=1,16 do
    for i=1,32 do
    love.graphics.draw(Tileset[MapTable[j*Maximum_X + i]], Start_X + 32*(i-1), Start_Y + 32*(j-1))
    end
end

end

Now it's clear for me that this is wrong and the right rule is MapTable[j*Maximum_X + i] but I get an error for it: "expected parameter type: expected userdata"

Was it helpful?

Solution

You can also use multi-dim tables. Something like:

local MapTable = {}
local Maximum_X, Maximum_Y = 32, 16
local Start_X, Start_Y = 64, 32

function love.load()
    for y = 1,Maximum_Y do
        local row = {}
        for x = 1,Maximum_X do
            table.insert(row,2)
        end
        table.insert(MapTable,row)
    end
end

function love.draw()
    for y,row in ipairs(MapTable) do
        for x,idx in ipairs(row) do
            love.graphics.draw(Tileset[idx], Start_X + 32*(x-1), Start_Y + 32*(y-1))
        end
    end
end

OTHER TIPS

As Alex shows it, the problem was not with the way how table works, but rather that I displayed the numbers on a wrong way. Tables can be used as one-dimensional arrays, and everything fine then.

Even though it's not a solution for using them as 2-dimensional array, the main problem is solved.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top