如何通过Lua中的目录结构编辑指定表格节点并返回新表格?
实现方案
方法1:直接修改原表格
如果允许直接修改原始表格,可通过循环遍历路径数组逐层定位目标节点,再修改其值:
-- 原始数据 local directory = {"File", "Documents", "txt_Page"} local table_dir = { Files = { File = { Documents = { txt_Page = "new" } } } } -- 定位目标节点的父节点 local current_node = table_dir.Files for i = 1, #directory - 1 do current_node = current_node[directory[i]] -- 可选:添加节点存在性检查,避免nil报错 if not current_node then error("路径节点不存在:" .. directory[i]) end end -- 修改目标节点的值 current_node[directory[#directory]] = "updated_content" -- 验证结果 print(table_dir.Files.File.Documents.txt_Page) -- 输出 updated_content
方法2:创建新表格(不修改原表格)
若需保留原表格不变,先对原表格做深拷贝,再修改拷贝后的表格:
-- 深拷贝函数 local function deep_copy(t) local copy = {} for k, v in pairs(t) do if type(v) == "table" then copy[k] = deep_copy(v) else copy[k] = v end end return copy end -- 原始数据 local directory = {"File", "Documents", "txt_Page"} local original_table = { Files = { File = { Documents = { txt_Page = "new" } } } } -- 创建深拷贝 local new_table = deep_copy(original_table) -- 定位并修改拷贝后的节点 local current_node = new_table.Files for i = 1, #directory - 1 do current_node = current_node[directory[i]] if not current_node then error("路径节点不存在:" .. directory[i]) end end current_node[directory[#directory]] = "new_edited_value" -- 验证结果 print(original_table.Files.File.Documents.txt_Page) -- 输出 new print(new_table.Files.File.Documents.txt_Page) -- 输出 new_edited_value
关键注意事项
- 遍历路径时需停在目标节点的父节点,通过父节点的键修改值,避免直接覆盖节点引用
- 建议添加节点存在性检查,防止因路径错误触发nil报错
- 若要保留原表格,必须使用深拷贝(浅拷贝仅复制顶层引用,修改子节点仍会影响原表格)
内容的提问来源于stack exchange,提问作者AronasRR
相关产品推荐
相关产品推荐

