I want to take the table "choices", shuffle it into "shuffled", then print both "choices" and "shuffled" contents (see code). I need to keep "choices" unmodified, to reuse it later.
When I run that, it first prints "1234" as "choices", and " " as "shuffled". However, when I run the shuffle(), it prints "shuffled" successfuly randomized, but then "choices" is printed as " ", so I guess it got wiped somehow in the process.
Then when I run shuffle() again, as "choices" is now empty, "shuffled" gets cleared too.
I don't understand how "choices" gets modified since all I do with it is setting its default value and printing it. I even tried to store it into "choices2" and call this new one for randomization, but even there, "choices" keeps getting wiped.
Furthermore, if I write "#tab - 1" instead of "#tab" in shuffle() 's For arguments, it only brings 3 numbers out of 4 to "shuffled", and the last number remains. When I do so, "choices" end up with this last number, which means "choices" somehow gets modified through shuffle(), even though it's not supposed to... any clue on why this happens?
Code: Select all
local shuffled = {}
local choices = {1,2,3,4}
local choices2 = choices
function love.load()
love.window.setMode(1200, 780, {})
end
function love.keypressed(key)
if key == "q" then
shuffled = shuffle(choices2)
end
end
function shuffle(tab)
local result = {}
for inc=1, #tab, 1
do
rand = love.math.random(#tab)
table.insert(result, tab[rand])
table.remove(tab, rand)
end
return result
end
function love.draw()
love.graphics.print(choices,0,0)
love.graphics.print(shuffled,0,30)
end