function call error (explained)

@Simeon Is this a problem or just the way it is and we have to code for it. I just ran into this and it took awhile to figure out why my code wasn’t working. So here’s a simple example of what I ran into.

It looks like the original variable values passed to a function aren’t changed if the passed variables to a function are changed in the called function. That seems correct. But it looks like the original vec2 variables passed to a function are changed if the passed variables are altered in the called function. That seems wrong.

viewer.mode=STANDARD

function setup()
    s1()
    s2()
end

function s1()
    p1=100
    p2=200
    
    print("original values dont change")
    print("before call  "..p1,p2)
    cross1(p1,p2) 
    print("after  call  "..p1,p2)
end

function cross1(v1,v2)
    v1=111
    v2=222
end


function s2()
    p1=vec2(100,100)
    p2=vec2(200,200)
    
    print("\
\
\
original values do change")
    print("before call  "..p1.x,p2.x)
    cross2(p1,p2) 
    print("after  call  "..p1.x,p2.x)
end

function cross2(v1,v2)
    v1.x=111
    v2.x=222
end

In Lua, tables are passed by reference, so I think that may explain what’s going on.

@RonJeffries I knew that about tables, but I did realize vecs were treated the same way. If that’s the case, I’ll just have to seperate the vec values and pass them as simple variables.

Modified my original program to account for the vecs being passed as reference and everything works OK. Just need to remember that in the future.

@dave1707 Codea’s Vec objects are ‘userdata’ types (essentially a pointer) so their behaviour is entirely native and they are also passed by reference.