lua - 在给定键表的情况下,是否有一种简单的方法来更改嵌套表中的值?
问题描述
所以我试图在给定键表的情况下更改嵌套表中的值
例子:
local DATA = {
Storage = {
Person_id = {
Money = 0;
Inventory = {
Item1 = 0;
}
}
}
}
local function ChangeData(ID, KeyTable, Value, Operation)
local StorageValue = DATA.Storage[ID].Data;
for _, Key in ipairs(KeyTable) do
StorageValue = StorageValue[Key];
end
if Operation == "+" then
StorageValue = StorageValue + Value;
elseif Operation == "=" then
StorageValue = Value;
end
end
ChangeData("person_id", {"Money"}, 5, "="};
ChangeData("person_id", {"Inventory", "Item1"}, 5, "="};
这成功地从嵌套表中获取值(并更改变量值),但不会更改嵌套表中的值。
...
解决此问题的唯一方法(我真的不想这样做)是对其进行硬编码。前任:
if Operation == "=" then
if #KeyTable == 1 then
DATA.Storage[ID].Data[KeyTable[1]] = Value;
elseif #KeyTable == 2 then
DATA.Storage[ID].Data[KeyTable[1]][KeyTable[2]] = Value;
--... and so on
所以我要问的是:在给定键表的情况下,是否有一种简单的方法来更改嵌套表中的值?
解决方案
您可以使用 删除表的最后一个值table.remove
,并将其保存为最后一个键。
然后,您可以按原样使用您的代码,只需将最后一个键索引添加到您的操作 if 语句体中。
local DATA = {
Storage = {
Person_id = {
Money = 0,
Inventory = {
Item1 = 5
}
}
}
}
local function ChangeData(ID, KeyTable, Value, Operation)
local StorageValue = DATA.Storage[ID]
local LastKey = table.remove(KeyTable)
for i, Key in ipairs(KeyTable) do
StorageValue = StorageValue[Key]
end
if Operation == "+" then
StorageValue[LastKey] = StorageValue[LastKey] + Value
elseif Operation == "=" then
StorageValue[LastKey] = Value
end
end
ChangeData("Person_id", {"Money"}, 5, "=")
ChangeData("Person_id", {"Inventory", "Item1"}, 5, "+")
print(DATA.Storage.Person_id.Money)
print(DATA.Storage.Person_id.Inventory.Item1)
此外,正如 Egor Skriptunoff 在评论中所述,请务必更改next, KeyTable
为ipairs(KeyTable)
以确保保留您的密钥顺序。
推荐阅读
- google-sheets - 如何从工作表中的下拉菜单中计算值
- php - 分页后将部分完全移动到新页面
- google-bigquery - 是否可以向 BigQuery 表添加/更新元数据?
- cypher-shell - 是否可以在 Cypher 中运行脚本?
- c++ - C++、WinAPI、ShellExecute、系统区别
- javascript - 为什么WebView在横向时不添加JavascriptInterface
- powershell - 从 powershell 使用 psexec64 运行 cmd 命令
- python - 如何使用 tensorflow 数据集访问图像
- c# - 如何使用 C# 在 Unity 中按住键盘上的一个键(例如:'W' 键)来移动对象?
- kotlin - 我需要在协程中操作 StateFlow 吗?