r/pico8•
VeryNaughtyBoy42

What is wrong with this code?

:p8:I Need Help:p8:

It's the basis of making a simple star field.

I create an array for an individual star (star), then an array of those arrays (stars). I use a loop to set the individual values for each star, and (for debugging) print out the values. They're different as expected. But immediately afterwards, they all become the same value - the value of the last item added.

Here's the output:

-0.6718
-0.5777
0.0473
-0.2585
0.6657
-0.0112
-0.392
-0.5346

-0.392
-0.5346
-0.392
-0.5346
-0.392
-0.5346
-0.392
-0.5346

And here's the code ...

function _init()
 star={0,0,0,0,0}
 stars={}
 numstars=4

 -- populate the array
 for c=1,numstars do
  add(stars,star)
 end

 -- create all the stars
 initstars()
end

function initstars()
 for s=1,numstars do
  initstar(s)
 end

 -- for debugging, now show the x inc and y inc values for all the stars
 print("")
 for s=1,numstars do
  print(stars[s][4])
  print(stars[s][5])
 end
end

function initstar(s)
 local ang=rnd(1)
 local spd=rnd(1)

 stars[s][1]=64 -- x
 stars[s][2]=64 -- y
 stars[s][3]=0  -- colour
 stars[s][4]=cos(ang)*spd  -- x inc
 stars[s][5]=sin(ang)*spd  -- y inc

 -- for debugging, print out the x inc and y inc values
 print(stars[s][4])
 print(stars[s][5])
end


Posted Jun 27, 2026, 7:25 AM UTC

86
Loading comments…