Lua(ComputerCraft)保存文件时无法将配方表嵌套插入主表求助
问题根源
存在两个核心错误导致你遇到的问题:
- 写入文件时使用了追加模式(
a)而非覆盖模式(w):你每次更新完配方主表后,没有直接覆盖旧的配方文件,而是把完整的新序列化主表拼到了旧文件末尾,最终文件内存在多个独立的Lua表结构。textutils.unserialize解析时只会读取第一个有效表,后续新增的配方不会被加载,每次运行都会把当前内存里的主表再次追加到文件末尾,就会出现你看到的多个独立表的情况。 - 存在冗余的重复文件读取逻辑:你写了两次完全相同的文件读取判断,第一次读取完成后已经关闭了文件句柄,第二次读取操作已关闭的句柄会返回空,极端情况下会清空已经读取到的旧配方数据。
修复方案
- 删除重复的文件读取代码段,仅保留一份读取逻辑即可
- 写入文件时将打开模式从
a改为w,直接用包含新配方的完整主表覆盖旧文件,保证文件内永远只有一个顶层主表,所有配方都嵌套在该表内。
修正后完整代码
-- 递归搜索相关依赖 local Deep = require "DeepPrint" -- 变量定义 -- 配方存储表 Recipes = {} -- 合成网格对应槽位 grid = {1,2,3,5,6,7,9,10,11}; -- 检查配方书是否存在,存在则读取已有数据 local readRecipe = fs.open("recipeBook.lua","r") if readRecipe == nil then print("recipe book not found") else recipeList = readRecipe.readAll() readRecipe.close() ok, Recipes = pcall(textutils.unserialize, recipeList) if not ok then return false, recipeList end if type(Recipes) ~= "table" then print("Main table not found, creating base table") Recipes = {} end end -- 获取当前合成网格内的材料信息 itemLayout = {} for key,value in pairs(grid) do turtle.select(value) if turtle.getItemDetail() then details = turtle.getItemDetail() table.insert(itemLayout,{ name = details.name, count = details.count, location = value }) end end -- 执行合成获取产物信息 turtle.select(16) turtle.craft() itemMade = turtle.getItemDetail() -- 检查对应产物的配方是否存在,不存在则新建表 if not Recipes[itemMade.name] then print("didnt find the table for item, creating new table") Recipes[itemMade.name] = {} else print("found recipe") end -- 更新配方信息 Recipes[itemMade.name]["components"] = itemLayout Recipes[itemMade.name]["quantityMade"] = itemMade.count -- 序列化后写入文件,此处改为w模式覆盖旧文件 local ok, str = pcall(textutils.serialize, Recipes) if not ok then return false, str else book = fs.open("recipeBook.lua","w") book.writeLine(str) book.close() end
内容的提问来源于stack exchange,提问作者Alex Howard
相关产品推荐
相关产品推荐

