【问题标题】:Modifies the key but doesn't actually modify the value?修改键但实际上不修改值?
【发布时间】:2014-10-24 21:59:59
【问题描述】:
players={}
players["foo"] =
        {
            wins = 0, deaths = 0, draws = 0, rounds = 0, bet = "None", rank = 0
        }
modify = function (stat, set, target)
    local player = players[target]
    local dictionary = 
            {
            ["wins"] = player.wins, ["deaths"] = player.deaths, 
            ["draws"] = player.draws, ["rounds"] = player.rounds, 
            ["bet"] = player.bet, ["rank"] = player.rank,
            }
    if dictionary[stat] then
        dictionary[stat] = set
        print(dictionary[stat])
        print(player.wins)
    end
end

modify("wins", 1, "foo")

上面提到的代码并没有真正发挥应有的作用。它修改了键“wins”,但它自身的值 (player[target].wins) 没有被修改。

【问题讨论】:

    标签: arrays lua indexing lua-table


    【解决方案1】:

    数值不是引用。当您复制它们而不是引用回到它们的原始位置时,您会得到副本。

    因此,当您分配 ["wins"] = player.wins 时,您不会在播放器表中获得对 wins 字段的引用。您正在将值复制到 dictionary 表中。

    如果要修改播放器表,则需要修改播放器表。

    该函数中的间接性也是完全没有必要的。您可以引用player[stat],就像引用dictionary[stat]一样。

    tbl.statsyntactic sugar[1] 对应于tbl["stat"]

    另外,如 lua 手册的§2.5.7 所示:

    tbl = {
        stat = 0,
    }
    

    一样
    tbl = {
        ["stat"] = 0,
    }
    

    当名称为字符串、不以数字开头且不是保留标记时。

    [1] 参见The type table 段落。

    【讨论】:

    • 哦,我认为它不起作用,因为 stat 将是一个字符串,谢谢!
    • tbl.stattbl["stat"] 的语法糖。查看我的编辑。
    猜你喜欢
    • 2019-07-26
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多