Hey everybody, I’ve been having a problem with inserting objects into arrays that have nil values in them. I wrote a snippet of code to show an example of how unpredictable the table insertion can be. All the code does is create an array of 24 places. It then fills the first twelve places with the corresponding numbers, leaves places 13 - 23 blank, and fills place 24 with the number 24. Touching the screen on the simulator will generate a random number between 13 and 23, and insert it into the array, but only if it has a nil value. By the time all the places are full (which takes many clicks), The end number of 24 will no longer be visible. If you click long enough, everything gets screwed up. I was wondering if I am doing something wrong or if this is some kind of bug, and if anyone knows a workaround to this. Thanks to anyone who can help. (The following is the code all the way to the end, posting it as code didn’t work.)
–Program to check the operation of inserting an object into a table
–Width and height of display
local W = display.contentWidth;
local H = display.contentHeight;
–Background to be touched to activate insertion of new table element
local BG = display.newRect(0, 0, W, H);
BG:setFillColor(255,0,0);
–Array to be used for insertion
local rocks = {};
–Number value to be used for insertion into array
local insert
–Give the first twelve places in the array sequential numerical values
for i = 1, 12 do
rocks[i] = i;
end
–Give the places from 13 to 23 in the array nil values, then give the 24th place a value of 24
for j = 13, 24 do
if(j ~= 24) then
rocks[j] = nil;
else
rocks[j] = 24;
end
end
–Print the values in the beginning array before it is modified
for k = 1, 24 do
print(rocks[k]);
end
–Array insertion function
function BGtouch(event)
if(event.phase == “ended”) then
insert = math.random(13, 23); --13 to 23 are the nil values of the table
if(rocks[insert] == nil) then
--Insert the value of the number picked between 13 and 23 into the
--same place in the array (Only if the existing value of that place was nil)
table.insert(rocks, insert, insert);
end
end
--Print the values of all places in the array after the background is touched
for k = 1, 24 do
print(rocks[k]);
end
end
–Event listener for background rectangle
BG:addEventListener(“touch”, BGtouch)