修改键,但实际上并不修改值?

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) 没有被修改。

点赞
用户258523
用户258523

数字值不是引用。当你复制它们时,你得到的是副本而不是引用到它们原来的位置。

因此,当你赋值 ["wins"] = player.wins 时,你并没有得到对 player 表中 wins 字段的引用。你正在将该值复制到 dictionary 表中。

如果你想修改 player 表,你需要直接修改 player 表。

此外,该函数中的间接过程完全是不必要的。你可以像引用 dictionary[stat] 一样引用 player[stat]

tbl.stat 是对语法的简化[1],等同于 tbl["stat"]

另外,在 Lua 手册的 §2.5.7 中可以看到:

tbl = {
    stat = 0,
}

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

是相同的,当名称是字符串、不以数字开头且不是保留字时。

[1] 请参见「The type table」段落。

2014-08-31 14:28:52