jeudi 2 janvier 2020

Effectively remove nil values from lua table

I am new to lua and fairly new to programming. I am trying to achieve the following.

I have a table of numbers from which I pick a random number.

myTable = {}

for i = 1 to 100 do 
   table.insert(myTable, i)
end

local numberChosen = myTable[math.random(#myTable)]

So far, so good. The next time a number is picked, I want that number to be removed from the table. I know lua doesn't remove values, they stay there as nil. So

table.remove(myTable, numberChosen)

Doesn't work as when I try to run the random function again, if the value is nil, I get "bad argument #1 to 'random' (interval is empty)"

I have tried creating a function like this:

function cleanTable(t)
    local  cleanTable = {}
    for k, v in ipairs(t)do
        if v ~= nil then
            table.insert(cleanTable, v)
        end
    end
    return cleanTable
end

myTable = cleanTable(myTable)

But that does't work either as the random function returns the same error. Can anyone help?




Aucun commentaire:

Enregistrer un commentaire