You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Lua如何读取文件中的table以实现ComputerCraft模组配方导入

实现方案

核心思路

不需要手动做复杂的字符串切割,直接用Lua的load函数执行每行的配置语句,同时配套配方一致性校验逻辑即可实现需求。

完整可运行代码(兼容ComputerCraft环境)

local recipes = {}

-- 二维配方表比对函数,校验两个配方是否完全一致
local function isSameRecipe(r1, r2)
    if #r1 ~= #r2 then return false end
    for i = 1, #r1 do
        if #r1[i] ~= #r2[i] then return false end
        for j = 1, #r1[i] do
            if r1[i][j] ~= r2[i][j] then return false end
        end
    end
    return true
end

-- 读取单个配方文件的方法,传入文件路径即可
local function loadRecipeFile(path)
    if not fs.exists(path) then error("文件不存在: "..path) end
    local file = fs.open(path, "r")
    while true do
        local line = file.readLine()
        if not line then break end
        -- 自动跳过空行
        line = line:trim()
        if #line > 0 then
            -- 构造临时执行环境,避免污染全局变量
            local env = {}
            local func, err = load(line, "recipeLine", "t", env)
            if not func then error("配置行语法错误: "..err.."\n出错行: "..line) end
            func()
            -- 处理读取到的配方
            for itemName, newRecipe in pairs(env) do
                if recipes[itemName] then
                    -- 已存在同名物品配方,校验是否冲突
                    if not isSameRecipe(recipes[itemName], newRecipe) then
                        error("物品 "..itemName.." 存在冲突配方,请检查配置文件")
                    end
                else
                    recipes[itemName] = newRecipe
                end
            end
        end
    end
    file.close()
end

-- 调用示例,按顺序加载所有配方文件
loadRecipeFile("file1")
loadRecipeFile("file2")

-- 执行完成后recipes变量就是你需要的结构

可调整点

  • 现有逻辑遇到配方冲突会直接抛出错误,你可以根据需求修改为打印警告、优先保留先加载/后加载的配方等逻辑
  • 如果需要支持配方文件内加注释,可在空行判断前新增逻辑过滤以#、--等符号开头的注释行

内容的提问来源于stack exchange,提问作者redstonegenious

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 11:06:02