2017-05-29 55 views
0

我沒有編程經驗,所以我不知道我應該把什麼標題。如何替換表中「鍵」的值?

但是,請幫助我,這是一件非常簡單的事情,我只是想換船['俾斯麥']到船隻['俾斯麥']。

例子如下

數據庫/船舶

local ships = { } 

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

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

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

return { ships=ships } 

然後

特殊數據/船舶

local data = require("Database/Ship") 

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

return data 

編輯:我如何做到這一點的智慧^ h GSUB,例如從其他人的代碼:

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

回答

0

所以如果我理解你的問題:你有一個規則,重命名像重命名'俾斯麥''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 

所以用這個解決方案,您CA n使用namingRules表定義命名。如果你想使用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 
+0

非常感謝,這是我所需要的。 –

3

如果你想使用'Bismarck'關鍵訪問data.ships['俾斯麥']數據,只是做

data.ships['Bismarck'] = data.ships['俾斯麥'] 
+2

而且不要忘了用'data.ships刪除以前的名字[「俾斯麥」] = nil' :) – Vlad

+0

我如何做到這一點與GSUB,我已經編輯了這個問題。 –

1

要回答你編輯的問題:

它在這裏使用gsub沒有意義。一旦用某個鍵存儲了某個表中的某個鍵,它將保持與該鍵相關聯,直到使用完全相同的鍵將其他內容存儲在同一個表中,或者直到整個表因爲您不再使用它而被垃圾收集爲止。

例如(如果你使用一些所謂的「弱表」,然後垃圾收集部分變得更爲複雜,但你不能在這裏使用它們。):

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