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?



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]".



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 |



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!


Thanks guys for your help! It works now, turns out the add(group,6) notation was what I was looking for
[Please log in to post a comment]