LUA:避免通过引用传递

问题描述 投票:1回答:3

我刚刚开始学习LUA,我遇到了一个问题,我不确定哪种方式可以“正确”解决。当我将Defold vmath.vector3传递给我的函数时,它似乎通过引用传递,因此被更改。 如果我将它乘以任何东西,那么这就解决了。 还有另一种更正确的解决方法吗?我不想修改我作为参数传递的原始向量。

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
function lua reference arguments defold
3个回答
0
投票

由于您将xy作为两个值返回,因此您可以以相同的方式实现两个分支而无需修改任何表:

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

3
投票

Defold提供了许多特殊的数据结构,这些结构在游戏开发中都非常有用:

  • vector3 - vmath.vector3(x,y,z),用于描述3D坐标系中的位置或方向
  • vector4 - vmath.vector4(x,y,z,w),用于颜色,色调等(红色,绿色,蓝色,alpha)
  • quat - vmath.quat()描述旋转的四元数
  • matrix4 - vmath.matrix4()一个4x4的值矩阵。对于视图和投影矩阵以及其他内容非常有用

所有以上内容均由Defold游戏引擎使用,但您也可以在其他游戏引擎中找到相同类型的数据结构。

上面的数据结构有一个共同点:它们是Lua类型userdata

print(type(vmath.vector3())) -- "userdata"

用户数据始终通过引用传递,这就是您看到所描述的行为的原因。 Defold确实提供了制作副本的方法:

local copy = vmath.vector3(original) -- copy the vector3 'original' local copy = vmath.vector4(original) -- copy the vector4 'original' local copy = vmath.quat(original) -- copy the quaternion 'original' local copy = vmath.matrix4(original) -- copy the matrix4 'original'


0
投票

你已经在else分支中有了一个解决方案:在对它们应用“修改”操作之前,你必须创建一个向量副本。

就其他选项而言,有可能提出一种使用代理表的方法,但它比创建副本要复杂得多。

© www.soinside.com 2019 - 2024. All rights reserved.