Makenshi
Makenshi

Reputation: 1053

filling 2dArrays with another 2DArray in Lua

is there a way to fill a 2d Array with another 2dArray in Lua? what im using right now is this

local T4 = {
    {0, 0, 0, 0, 0},
    {0, 0, 1, 0, 0},
    {0, 1, 1, 1, 0},
    {0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0}
};

function myFunc()
local Pieces = {}

        for x = 1, 5 do
        Pieces[x]={}
           for y = 1, 5 do
           Pieces[y][x] = T4[y][x]--the error is probably here
           end
        end
end

but this is not working,ive got a good reason to do this and its because this process gets repeated a lot of times so using T4 is not an option

also im not getting an error,the program just stops there,so any idea how to do this?

Upvotes: 0

Views: 955

Answers (1)

Mud
Mud

Reputation: 28991

You've got your indexes messed up:

function myFunc()
    local Pieces = {}
    for y = 1, 5 do
        Pieces[y]={}
        for x = 1, 5 do
            Pieces[y][x] = T4[y][x]
        end
    end
    return Pieces
end

You could copy any table using something like this:

function copytable(t)
    local copy = {}
    for key,val in pairs(t) do
        if type(val) == 'table' then
            copy[key] = copytable(val)
        else
            copy[key] = val
        end
    end
    return copy
end

This is off the top of my head so use with cation. It definitely doesn't deal with cyclic references (a table which contains a reference to the same table).

Upvotes: 4

Related Questions