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

Lua报错:调用insert时参数1无效(期望table,实际得到nil)

背包物品堆叠脚本错误修复

你的脚本核心错误是Lua大小写敏感导致的键名不匹配:初始化堆叠条目时用的是小写items,但后续插入工具时误用了大写Items,程序找不到对应的表,因此报错。

修复后的完整代码

local function scanItems()
    local items = {}
    
    -- 合并遍历背包和角色的工具,减少冗余代码
    for _, parent in ipairs({backback, char}) do
        for _, tool in pairs(parent:GetChildren()) do
            if tool.ClassName == "Tool" then
                table.insert(items, tool)
            end
        end
    end
    
    local invItems = {}
    
    for _, tool in pairs(items) do
        local itemEntry = invItems[tool.Name]
        if itemEntry then
            itemEntry.Count += 1
            -- 统一使用小写items(和初始化时的键名保持一致)
            table.insert(itemEntry.items, tool)
        else
            invItems[tool.Name] = {
                Count = 1;
                items = {tool};
            }
        end
    end
    
    print(invItems)
end

task.wait(5)
scanItems()

额外优化说明

  • 合并了两次工具遍历逻辑,避免重复代码
  • 用局部变量itemEntry减少重复索引查找,提升运行效率
  • 全程保持键名大小写一致(你也可以统一改成大写Items,只要前后对应即可)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 02:52:06