Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

function call error (explained)

dave1707dave1707 Mod
edited May 6 in Bugs Posts: 10,055

@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("\n\n\noriginal 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

Comments

  • Posts: 1,364

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

  • dave1707dave1707 Mod
    Posts: 10,055

    @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.

  • dave1707dave1707 Mod
    Posts: 10,055

    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.

  • edited May 6 Posts: 421
    @dave1707 Codea's Vec objects are 'userdata' types (essentially a pointer) so their behaviour is entirely native and they are also passed by reference.
Sign In or Register to comment.