Steve Patterson
Steve Patterson

Reputation: 163

How to work with tables in Corona SDK

I have a sort of general question but i think that if I tried to be too specific I would only make it very confusing. So basically what I want to know is this:

When you create a table in Corona/Lua you can put pretty much an unlimited number of things in it correct?

So say i create a table called

   rectangles = {};

and then i put a bunch of instances of rectangles in it. If i wanted to change a property of ALL the rectangles at once, how could I do it?

I understand how it would work with a set number of items in the table, like:

    for i = 1, 10 do 
        rectangles[i] = display.newImage("rectangle.png");

then to change all of the images x positions for instance you would simply say

     rectangles[i].x = 20;

but how would you change a property of all items in the array without knowing how many there are, as in you didnt give an upper bound, and cant because the table is always growing?

Upvotes: 1

Views: 9008

Answers (2)

cctan
cctan

Reputation: 2023

For arrays that have only one kind of elements you can use #rectangles for element count.

for i = 1, #rectangles do 
        rectangles[i] = display.newImage("rectangle.png");
end

Regarding the youtube example,

if you add element into rectangles like this:

rectangles[b]=b;

what it actually does is

rectangles["083DF6B0"]=b"

you see when a display object b is used as a key it is converted into a hex string.

in addition, you would need to use pairs to go over each element as they are
keys (e.g. array.length,array.width,array.weight..) rather than index (e.g. array[2],array[3]..)

for key,value in pairs(rectangles) do
    print(key); --prints 083DF6B0
    print(value); --prints 20
    rectangles[key]=30;
end

Upvotes: 4

Corbin March
Corbin March

Reputation: 25714

It depends on how you're storing items in the table. If you're storing by index (as in your example), you can use ipairs to iterate over indexes and values:

for index,value in ipairs(rectangles) do
    value.x = 20
    --or
    rectangles[index].x = 20
end

If you're storing by key (as in the youtube video you mention in a comment), iterate using pairs:

for key,value in pairs(rectangles) do
    value.x = 20
    --or
    rectangles[key].x = 20
end

Just don't store items using both index and keys, unless you know what to expect.

Upvotes: 2

Related Questions