Gooner
Gooner

Reputation: 387

how to use table elements

I'm displaying titles of movies as letter images e.g. A separate image for each letter. Each letter can then be dragged in a space/container. this is my code for displaying the container

posX = {}
posY = 124
px = 10
containers = {}
for i = 1, #letters do
    if(letters[i]==" ") then
        px = px + 10
        -- print(posX[i])
        -- table.remove(posX, posX[i])
    else
    posX[i] = px
    containers[i] = display.newImage( "Round1_blue_tileEnlarged 40x40.png",      posX[i],posY )
    px = px + 40
    end
end

As you can see I am checking for a space e.g if batman begins was the title, I have no problems if the title is a single word, but adding the space is adding another element to my array that is causing an error when im placing an objecet in my containers. You can see in the 'if' im just adding a space but I dont want this to be an element of my table posX

Upvotes: 0

Views: 86

Answers (1)

catwell
catwell

Reputation: 7020

I am not sure I understand your question well but if I do here is your problem: you are using i as the index in posX but i is incremented by the for loop even for spaces. That results in holes in the posX and containers tables.

You can fix that in several ways, here is a trivial one:

posX = {}
posY = 124
px = 10
containers = {}
local j = 1
for i = 1,#letters do
    if(letters[i]==" ") then
        px = px + 10
    else
        posX[j] = px
        containers[j] = display.newImage( "Round1_blue_tileEnlarged 40x40.png", posX[j],posY )
        px = px + 40
        j = j + 1
    end
end

You could also use #posX instead of j.

Upvotes: 3

Related Questions