Terrence The Alien
Terrence The Alien

Reputation: 19

Lua Acessing table values within nested table

I'm trying to test certain variables on a grid made out of nested tables. However no matter what I try it wont give me the values stored within the variables only the data type or a nil value

y = {}
for _y = 0,16 do
    for _x = 0,16 do
        x = {}
        x.x = _x
        x.y = _y
        x.v = flr(rnd(2))

        if x.x < 1 or x.x > 14 then
            x.v = 3
        end


        if x.v == 0 then
            x.v = "."
        elseif x.v ==1 then
            x.v = ","
        else
            x.v = "0"
        end
        add(y,x)
    end
end

I've tried accessing the value using

print(t[1][3])

But this only prints back a nil value, how would I code this to show whats stored within the value within these two tables?

Upvotes: 1

Views: 861

Answers (2)

DarkWiiPlayer
DarkWiiPlayer

Reputation: 7046

You want to create a 2-dimensional table, but only create a 1-dimensional one.

Fix your code to look somewhat like this

y = {}
for _y=1,16 do
    y[_y] = {}
    for _x=1,16 do
        y[_y][_x]= "your data"
    end
end

Upvotes: 0

hjpotter92
hjpotter92

Reputation: 80629

You have the nesting as follows:

y = {x_1, x_2, x_3, ...}

where, each of x_i is of the form:

x = {
  x = p,
  y = q,
  v = r
}

so, you will have the indexing for each x element as y[i], and each y[i] contains 3 attributes:

print(y[1].x)

will give you x_1.x

Upvotes: 2

Related Questions