如何在 table 中替换 "key" 的值?

How to replace the value for a "key" in a table?

我没有编程经验,不知道标题应该写什么

但是请帮帮我,这件事真的很简单,我只是想把ships['亿斯麦']改成ships['Bismarck'].

示例如下

Database/Ship

local ships = { }

----------------------------------------------

ships['俾斯麦'] = {
    index=1, country='Germany', class='Bismarck-class'
}

----------------------------------------------

return { ships=ships }

然后

特别Data/Ship

local data = require("Database/Ship")

data.ships['俾斯麦'] = 'Bismarck'

return data

编辑:如何使用 gsub 执行此操作,例如来自其他人的代码:

local function replaceShipName(name)
    name = name:gsub('俾斯麦', 'Bismarck')
    name= name:gsub('提尔比茨', 'Tirpitz')
    return name
end

如果您想使用 'Bismarck' 作为键访问 data.ships['俾斯麦'] 中的数据,只需执行

data.ships['Bismarck'] = data.ships['俾斯麦']

回答您编辑过的问题:

这里用gsub没有意义。一旦您使用某个密钥将某些内容存储在 table 中,它就会与该密钥保持关联,直到您使用完全相同的密钥将其他内容存储在相同的 table 中,或者直到整个 table 收集垃圾是因为您不再使用它了。

(如果您正在使用名为 "weak tables" 的东西,那么垃圾收集部分会变得更加复杂,但您不会在这里使用它们。)

例如:

local t = {}

t["a"] = "A value"
print(t["a"]) -- "A value"
print(t["b"]) -- nil

t["b"] = t["a"]
print(t["a"]) -- "A value"
print(t["b"]) -- "A value"

t["a"] = nil
print(t["a"]) -- nil
print(t["b"]) -- "A value"

t = nil -- You can't access the table now, so it will be garbage collected at some point

所以如果我理解你的问题:你有一个重命名规则,比如将 '俾斯麦' 重命名为 'Bismarck'

local namingRules = {
    '俾斯麦' = 'Bismarck',
    '提尔比茨' = 'Tirpitz'
}

--do renaming for all data
local shipsData = data.ships
for key, value in pairs (shipsData) do
  local newKey = namingRules[key]
  if (newKey  ~= nil) then
    --if data should be renamed
    shipsData[newKey] = shipsData[key]
    shipsData[key] = nil
  end
end

因此,通过此解决方案,您可以使用 namingRules table 定义命名。如果你想使用gsub解决方案:

local shipsData = data.ships
for key, value in pairs (shipsData) do
  local newKey = replaceShipName(key) -- this is your replaceShipName function
  if (newKey ~= nil and newKey ~= key) then
    shipsData[newKey] = shipsData[key]
    shipsData[key] = nil
  end
end