Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How do I make a function completely clear a table?

Asked by
chrono2 189
7 years ago

I'd like to be able to make this function clear out the table, or overwrite it instead of adding onto it. How would I go about that? I couldn't just use table.remove(rolls) could I?

sides = 6
numdice = 1

rolls{}


function rollthedice()
    for i = 1, numdice do
        table.insert(rolls, math.random(1,sides))
    end
end

1 answer

Log in to vote
2
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
7 years ago
Edited 7 years ago

For many purposes, you can just replace the variable with a new empty table:

rolls = {}

This doesn't actually affect the old object, meaning if you had something like this:

local old_rolls = rolls
rolls = {}
print(#old_rolls) --> 5 or whatever

the ones referencing the old table won't be cleared. Normally you shouldn't have that case.

If you have a list, you can repeatedly table.remove from it:

while #rolls > 0 do
    table.remove(rolls)
end
1
whiel -> while 1waffle1 2908 — 7y
0
oops BlueTaslem 18071 — 7y
Ad

Answer this question