Roblox-尝试索引字段“?” (一个nil值)运行模块功能的问题

时间:2019-01-12 00:28:57

标签: lua roblox

我试图建立一个数据存储区并更改播放器数据的值,但是在获取脚本以运行该功能时遇到了问题。我将粘贴遇到问题的代码,并标记出现错误的行。对于任何菜鸟错误,我深表歉意,这是我第一次使用Lua和Roblox编写游戏。我认为如何调用statNamestatName中的"Wheat"可能不存在问题,但是我不知道如何调用它,或者为什么它不在那里。

这是模块脚本中的相关内容:

function PlayerStatManager:ChangeStat(player, statName, value)

    local playerUserId = "Player_" .. player.UserId
    assert(typeof(sessionData[playerUserId][statName]) == typeof(value), "ChangeStat error: types do not match")  <--this line
    if typeof(sessionData[playerUserId][statName]) == "number" then
        sessionData[playerUserId][statName] = sessionData[playerUserId][statName] + value
    else
        sessionData[playerUserId][statName] = value
    end

end


-- Function to add player to the 'sessionData' table

local function setupPlayerData(player)

    local playerUserId = "Player_" .. player.UserId
    local data
    local success, err = pcall(function()
        playerData:UpdateAsync(playerUserId, function(playerData)
            data = playerData
        end)
    end)

    if success then
        if data then
            -- Data exists for this player
            sessionData[playerUserId] = data
        else
            -- Data store is working, but no current data for this player
            sessionData[playerUserId] = {Money=0, Wheat=0, Silo=0, Feeders=0, Chickens=0}
        end
    else
        warn("Cannot set up data for player!")
    end
end

这是使用模块脚本的脚本中的相关内容:

local SrvrStats = require(game.ServerStorage.moduleScript)

SrvrStats:ChangeStat(player, 'Wheat', playerWheat.Value) <-- this line

1 个答案:

答案 0 :(得分:0)

尝试一下:

local PlayerStatManager = {}

PlayerStatManager.ChangeStat = function(player, statName, value)

    local playerUserId = "Player_" .. player.UserId
    assert(typeof(sessionData[playerUserId][statName]) == typeof(value), "ChangeStat error: types do not match")  <--this line
    if typeof(sessionData[playerUserId][statName]) == "number" then
        sessionData[playerUserId][statName] = sessionData[playerUserId][statName] + value
    else
        sessionData[playerUserId][statName] = value
    end

end


-- Function to add player to the 'sessionData' table

PlayerStatManager.setupPlayerData = PlayerStatManager(player)

    local playerUserId = "Player_" .. player.UserId
    local data
    local success, err = pcall(function()
        playerData:UpdateAsync(playerUserId, function(playerData)
            data = playerData
        end)
    end)

    if success then
        if data then
            -- Data exists for this player
            sessionData[playerUserId] = data
        else
            -- Data store is working, but no current data for this player
            sessionData[playerUserId] = {Money=0, Wheat=0, Silo=0, Feeders=0, Chickens=0}
        end
    else
        warn("Cannot set up data for player!")
    end
end

return PlayerStatManager