Log In  

I'm having trouble with a for loop. The code runs but it doesn't work as desired. Here's the code:

function pikmin_create(n)
    g = 1
    for group in all(pikmin.sprite) do
        for i = 1,n do      

            if g == 1 then
                add(pikmin.sprite[group],6)
            elseif g == 2 then
                add(pikmin.sprite[group],8)
            elseif g == 3 then
                add(pikmin.sprite[group],10)
            end

        end 
        g+=1    
    end
end

pikmin.sprite is initalized in function _init() as follows:

pikmin = {
        sprite = {{},{},{}}
}

This should assign every group/subtable in pikmin.sprite a different sprite. However the assignment doesn't work (as the default 0 sprite gets printed).
What am I doing wrong?

P#127655 2023-03-27 12:42

You're mixing your variables up a bit. "group" is assigned in the loop using "for group in all(pikmin.sprite)" but you're trying to treat it like a number using it as an index in "pikmin.sprite[group]".

Just based on this snippet, it looks like you potentially mean to be doing "pikmin.sprite[g]" instead of "pikmin.sprite[group]".

P#127666 2023-03-27 14:33

There are two styles of for loops that are mixed up in your code:

for group in all(pikmin.sprite) do
 -- group is each table from pikmin.sprite
 -- can be used directly
 add(group,6)
end

for gi=1,#pikmin.sprite do
 -- gi is 1, 2, 3
 -- can be used as index (key)
 add(pikmin.sprite[gi],6)
end
P#127668 2023-03-27 14:37

There may be more issues with the logic of your code.
What result do you want to get? You mentioned «assign every group in pikmin.table a different sprite», but the code is not doing that.
Give us some more info!

P#127669 2023-03-27 14:41

Thanks guys for your help! It works now, turns out the add(group,6) notation was what I was looking for

P#127678 2023-03-27 17:07

[Please log in to post a comment]