lualua-tableroblox-studio

Roblox Studio Lua: Variable changing without being referenced


This is my module script:

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 

This is how I've implemented it in my main script.

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

The players table became empty after calling getRoleAssignments(players, roles) even though I have not referenced it at all. I have only passed it into the function, which should create a local copy as stated in the docs. However, the players table is empty after I called the function shown by the print statement when ran.

I expect the players table to retain its data. I've tried to making sure the identifiers are not the same which did not work. I've tired storing the players table in a separate local variable and passing that into the function instead, it did not work. Not calling the function does result in the players table retain its data though.


Solution

  • it appears that lua just gives a pointer to the table location instead of giving a copy. https://onecompiler.com/lua/42e9nrkup

    a way to fix this could be by copying the table yourself by doing:

    local copy = table.pack(table.unpack(playersToAssignRoles))