Quick Links: Download Gideros Studio | Gideros Documentation | Gideros community chat | DONATE
equating variable to array — Gideros Forum

equating variable to array

When we equate a variable to an array and do something with a variable, will this affect the array to which we equated it?

for example:
bim={0,1,2}

bom=bim

bom[1]=0



I wrote a lot of code, and in one function we do exactly this thing, somehow it affects the main array

I haven’t met this one before

I always thought that the variable and the array are not linked when equating and accessed this array through _G []

I want to know for sure how it works

Comments

  • MoKaLuxMoKaLux Member
    Accepted Answer
    yes I tested with your example and indeed this changes the value in the original table, I think it is expected!?

    To only change the bom table you need to make it separate from bim, something like:
    -- tables
    local bim = {0, 1, 2}
    local bom = {}
     
    for i = 1, #bim do
    	bom[i] = bim[i]
    end
     
    print(bim[1]) -- 0
    print(bom[1]) -- 0
     
    bom[1] = 3
     
    print(bim[1]) -- 0
    print(bom[1]) -- 3
    Hope this answers your question.
    my growING GIDEROS github repositories: https://github.com/mokalux?tab=repositories
  • thanks, for some reason I always thought that it works exactly as I described above :|

    strange that I have not encountered this problem before
  • keszeghkeszegh Member
    Accepted Answer
    arrays are actually only pointers, to use the terminology from other languages.
  • hgy29hgy29 Maintainer
    Accepted Answer
    Yes as others said earlier, table/arrays are assigned by reference. If you do want a separate copy of a table, that's called a clone. See http://lua-users.org/wiki/CopyTable
  • thanks for answers guys!
    finally I figured it out o:)
Sign In or Register to comment.