Subnot

Ive run into a glitch while coding a game.
some how well I’ll show you.

This isnt the games code but an example of what the glitch is.

-- subnot
displayMode(OVERLAY)

function setup()
    realtable = {color(0,0,0,0)}
end

-- This function gets called once every frame
function draw()
    -- This sets a dark background color 
    background(40, 40, 50)
if rt == nil then
        rt = realtable
        rt[#rt + 1] = color(255, 0, 0, 255)
    end

    -- This sets the line thickness
 
    for display = 1,#realtable do
    fill(realtable[display].r,realtable[display].g,realtable[display].b,realtable[display].a)
    rect(WIDTH/2,0,50,50)
end
    -- Do your drawing here
    
end

I used to be able to highlight the code. Any way the table that’s being used is supposed to be the realtable not the other table rt. So how is rt’s value being passed into the realtable? Shouldnt the realtable be unaltered? Nothing was added to it.

@Rdo When you post code, put 3 ~'s on a line before and after your code. As for your problem, when you do rt=realtable, you’re making rt and realtable be the same table. Anything you do to one, you do to the other. If you want them to be seperate tables, then do an actual copy of each entry to the other table.

You’re expecting the array to have value semantics, but in Lua, only the core variable types — strings, numbers etc — have value semantics, everything else, arrays, and custom objects (here the Codea-defined color object) has reference semantics. That means that if you say myTable2 = myTable1, myTable2 is not an independent copy of the table, as you’re expecting, it’s a reference to myTable1. So any changes you make to myTable2 are actually being applied to myTable1 (slight over-simplification here, both myTable1 and myTable2 are references to a table object somewhere in memory). If you want an independent copy of a table, you need to implement some form of “deep copy”, essentially iterating through the table, copying each element one by one. You can do a forum search for deep copy, or, if the table is just “one dimensional” (doesn’t contain other tables nested inside), write your own. But, note that the color object itself also follows reference semantics, so you’d need to instantiate a new color object to have an independent copy: myColor2 = color(myColor.r, myColor.g, myColor.b, myColor.a)