Roblox Studio Lua:无需引用即可更改变量

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

这是我的模块脚本:

local phases = {}

local function getRoleAssignments(playersToAssignRoles, roles)
     --Assigns a random player to each role then removes player from list so player can't get two roles.
     --Not every role will be assigned if not enough players
    for role, _ in pairs(roles) do
        local player = nil

        if 0 < #playersToAssignRoles then
            player = playersToAssignRoles[math.random(1,#playersToAssignRoles)]
        end

        roles[role] = player
        table.remove(playersToAssignRoles,table.find(playersToAssignRoles,player))
    end

    return roles
end


function phases.loadGame(players, roles)
    local map = getRandomMap()
    print(players) --Prints a full table (just one player because just me testing)
    local roleAssignments = getRoleAssignments(players, roles)
    print(players) --Prints an empty table
end 

这就是我在主脚本中实现它的方式。

local playersPlaying = Players:GetPlayers()
roles = Phases.loadGame(playersPlaying, roles)

调用

players
后,
getRoleAssignments(players, roles)
表变空,尽管我根本没有引用它。我仅将其传递到函数中,该函数应该按照文档中的说明创建本地副本。但是,当我在运行时调用 print 语句显示的函数后,
players
表为空。

我希望

players
表保留其数据。 我试图确保标识符不相同,但没有成功。 我厌倦了将
players
表存储在单独的局部变量中并将其传递到函数中,但它不起作用。 不调用该函数确实会导致
players
表保留其数据。

lua lua-table roblox-studio
1个回答
0
投票

看来lua只是给出了一个指向表位置的指针,而不是给出了一个副本。 https://onecompiler.com/lua/42e9nrkup

解决此问题的方法可以是通过执行以下操作自行复制表格:

local copy = table.pack(table.unpack(playersToAssignRoles))
© www.soinside.com 2019 - 2024. All rights reserved.