0

I have no idea why this is not working. I am trying to delete the numbers in the table one by one (the randomCheck picks a number from the table and I want to delete that exact number) when I press the button 'MyButton'

math.randomseed(os.time())

_X = display.contentCenterX
_Y=display.contentCenterY

local numbers = {1,2,3,4,5,6,7,8,9,10}
local randomCheck =  numbers[ math.random( #numbers) ]
local text = display.newText(""..randomCheck.."",_X,_Y,"Helvetica",50)

function removeNumber()
    for i = 1, 10 do
        if(randomCheck == i ) then 
            table.remove(numbers,i) 
            text.text = (""..i.."") 
        end 
    end
end

myButton = display.newRect(_X,_Y+100,100,80 )
myButton:addEventListener("tap", removeNumber)
  • Did nothing show in your errorlog? I'd expect it to abort upon the moment when you try to call a nill field `remove` of a numeric array `{1,2,3...}` which shadows the global variable `table` in your chunk of code. – Dimitry May 04 '18 at 14:37
  • Also, considering your removal loop, it is either unnecessary (can be replaced by `i = math.random(#table)` ), or incorrect ( see https://stackoverflow.com/a/12397571/4687565 ) – Dimitry May 04 '18 at 14:43
  • Try renaming your table to a something that is not reserved by Lua. – kingJulian May 04 '18 at 14:59
  • Are the number in `numbers` unique? If not, you'd need a more robust algorithm. – Tom Blodget May 04 '18 at 22:43

1 Answers1

0

In your loop, instead of

if(randomCheck == i)

use

if(randomCheck == numbers[i])

But all of that work is really unnecessary.

Instead of

local randomCheck =  numbers[math.random( #numbers)]

use

local randomIndex =  math.random(#numbers)
local randomCheck =  numbers[randomIndex]

Then you can just

table.remove(numbers, randomIndex)
Doug Currie
  • 40,708
  • 1
  • 95
  • 119