values leaving a function aren't the same outside the function

Hi i’m new to the forums and to Codea.

So i’m seeing weird results. I have a 6x6 grid and i assign the starting point within the grid and i have a function that gives me a random exit point in the grid that is at minimum 5 squares away. The problem is sometimes when i run and rerun (using the little recycle circle arrow) the Exit values don’t match the values just before the findExit returns ex and ey.

This is from the grid:init for the class


    local exitx, exity = 0,0
    local hx,hy = 0,0
    hx,hy = math.random(1,6), math.random(1,6)
    exitx, exity = findExit(hx,hy)
    print("exit " .. exitx .. "," .. exity)

This is my findExit function…i have tried different things, but i get weird results sometimes. you can see the different values in the print(“end” and print(“exit” sometimes, and i can’t for the life of me figure out why. Also, if i do it as below with the 2nd return ex, ey i sometimes get nil values in the exitx or exity variables, despite the ex and ey variable showing a value

function findExit(sx,sy)
    print("start " .. sx .. "," .. sy)
    local ex,ey = math.random(1,6), math.random(1,6)
    if math.abs(sx-ex) + math.abs(sy-ey) >= 5 then
        print("end " .. ex .. "," .. ey)
        return ex, ey    
    else 
        findExit(sx,sy)
    end
    --return ex, ey
end

so to add a little more. For Example

sx, sy = 1,1
ex, ey = 4,6 (this value is valid, over 3 and up 5 = 8 spaces)
exitx, exity = 2,2 (this value is not valid, but for some reason shows up in the results after the function call. 2 spaces away)

your findExit function is bugged. Try to follow the data paths and cases. Then you will at least change that:

function findExit(sx,sy)
    print("start " .. sx .. "," .. sy)
    local ex,ey = math.random(1,6), math.random(1,6)
    if math.abs(sx-ex) + math.abs(sy-ey) >= 5 then
        print("end " .. ex .. "," .. ey)
        return ex, ey    
    else 
        return findExit(sx,sy)
    end
end

but i dont like these recursive calls anyway… That ends up with a stack overflow some times.

@DanRiverBrew - try using a while loop, it is more efficient than recursion and avoids the error

function findExit(sx,sy)
    print("start " .. sx .. "," .. sy)
    local ex,ey = math.random(1,6), math.random(1,6)
    while math.abs(sx-ex) + math.abs(sy-ey) < 5 do
         ex,ey = math.random(1,6), math.random(1,6)  
    end
    print("end " .. ex .. "," .. ey)
    return ex, ey 
end

@Jmv38 - I don’t think the recursive call will overflow the stack because it is what is known as a tail call. I’ll leave it to the Lua manual to explain!

Thanks a bunch guys for taking the time to respond. I can’t wait to try your suggestions

Cheers!