Hello, I'm kinda new to Pico-8 and programming in general, and I'm trying to make a tetris game from scratch. Everything was going ok, but there's one thing that's bugging me: if I try to change a table that's a copy of another one, the original table also gets changed. I've made a simpler code to test if the problem was with some other function I wrote, but the problem persists. Here's the code:
function _init() test={1,2,3} end function _update() if btnp(4) then local t=test t[1]=0 end end function _draw() cls() for i=1,count(test) do print(test[i],40+i*8,60,7) end end |
If I execute this code and press Z, the first element of test changes, even though I only changed the local table t. What am I missing here?
That's just how lua works I'm afraid. When you assign t=test you're just making t have the same reference as test, not copying values over from it. Assigning numerical values versus assigning tables to variables just works differently.
You could iterate over each value in the table and copy them across like this
for key, value in pairs(test) do t[key] = value end |
But keep in mind that the same issues with reassigning tables will apply if any of the elements in your table are also tables!
I found this out too. There's information here that may help you:
[Please log in to post a comment]