functionluareferenceargumentsdefold

LUA: Avoiding passing by reference


I'm just starting to learn LUA and I've got an issue that I'm unsure which way to "properly" solve. When I pass a Defold vmath.vector3 to my function it appears to be passed by reference and is therefore altered.
If I multiply it by anything this is solved however.
Is there another more correct way to solve this? I don't want to modify the original vector that I pass as an argument.

function M.get_nearest_tile(x, y)
    if y then -- if we've got 2 inputs, use x & y
        x = math.floor(x / M.TILE_SIZE)
        y = math.floor(y / M.TILE_SIZE)
        return x, y
    else -- if we've only got 1 input, use as vector
        local vec = x * 1 -- multiplying by 1 to avoid modifying the real vector
        vec.x = math.floor(vec.x / M.TILE_SIZE) 
        vec.y = math.floor(vec.y / M.TILE_SIZE) 
        return vec.x, vec.y
    end
end

Solution

  • Since you're returning x and y as two values, you could implement both branches the same way without modifying any tables:

    function M.get_nearest_tile(x, y)
        local newX, newY
        if y then -- if we've got 2 inputs, use x & y
            newX = math.floor(x / M.TILE_SIZE)
            newY = math.floor(y / M.TILE_SIZE)
        else -- if we've only got 1 input, use as vector
            newX = math.floor(x.x / M.TILE_SIZE)
            newY = math.floor(x.y / M.TILE_SIZE)
        end
        return newX, newY
    end