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
相关产品推荐
相关产品推荐

