Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

ModuleScript variables change back to 0 immediately after being changed?

Asked by 4 years ago
Edited 4 years ago

Basically I have a data module with a table in it for player stats

local DataModule = {}
local PlayerData = {}

function DataModule.AddPlayer(player, data) -- adds a player to the PlayerData Table (Do this when a player joins)
    PlayerData[player] = data
end

function DataModule.AddData(player)
    local dataTable = PlayerData[player]
    for i, v in pairs(dataTable) do
        v = v + 1
        print(i,v)
    end
    for i,v in pairs(dataTable) do
        print(i,v)
    end
end

return DataModule

Another script waits for players to join and creates an entry in the table with their new data

local DataModule = require(game.ServerScriptService.DataModule)
local Players = game:GetService("Players")


local newData = {hasBag = 0, bagSpace = 0, maxBagSpace = 0}

function PlayerJoined(player)
    DataModule.AddPlayer(player, newData)
end


Players.PlayerAdded:Connect(PlayerJoined)

This works and I can check and print that the 3 values are created and all equal 0.

Just for testing sake I then made a button that I'm trying to get to increase the values.

local db = false
local DataModule = require(game.ServerScriptService.DataModule)


local function onTouch(hit)
    if hit.Parent:FindFirstChild("Humanoid") and db == false then
        db = true
        local player = game.Players:FindFirstChild(hit.Parent.Name)
        DataModule.AddData(player)
        wait(1)
        db = false
    end
end

script.Parent.Touched:Connect(onTouch)

As you can see in the AddData function from the ModuleScript, it is just attempting to change the value of each entry by 1. You can see I have 2 print checks in it. The first one, during the loop that increases the value, returns the increased value. The second loop immediately after updating all the values, returns them all back at 0.

Am I missing something with scope or what's going on?

Thanks

1 answer

Log in to vote
0
Answered by 4 years ago
for i, v in pairs(dataTable) do
    v = v + 1 --> table not changed, only the integer stored in variable 'v'
    print(i,v)
end
for i,v in pairs(dataTable) do
    print(i,v) --> v is still 0 because table not changed
end

v is a temporary variable that holds the value stored in the table newData. It's not a pathway to the table, it's just an integer, so changing it won't change the table. To change the table, you need to reference it using dataTable[i]:

for i, v in pairs(dataTable) do
    dataTable[i] = v + 1 -- actually changing the table
end
for i,v in pairs(dataTable) do
    print(i,v) --> v is 1 because table updated
end
1
Ahh man thankyou so much! Deputy_McNugget 14 — 4y
Ad

Answer this question