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

Lua迭代器参数错误:期望Table却得到String的问题排查

Lua车辆数据菜单生成报错排查与解决

原始数据与问题代码

车辆数据结构

result = { 
    [1] = { ["identifier"] = MMK18495,["vehicles"] = {"vehN":"Caracara 4x4","vehM":"caracara2","totals":3},["id"] = 1,} ,
    [2] = { ["identifier"] = MMK18495,["vehicles"] = {"vehN":"Sandking SWB","vehM":"sandking2","totals":3},["id"] = 2,} ,
    [3] = { ["identifier"] = MMK18495,["vehicles"] = {"totals":5,"vehN":"Caracara 4x4","vehM":"caracara2"},["id"] = 3,} ,
}

尝试生成菜单的代码

for i=1, #result, 1 do
    local ownedcars = result[i].vehicles
    print(dump(ownedcars))
    for _,v in pairs(ownedcars) do  -- <- 错误发生在此处
        menu[#menu+1] = {
            header = " Model "..v.vehM.." Name "..v.vehN.." quantity"..v.totals,
            txt = "",
        }
    end
end

错误提示

bad argument #1 to 'for iterator' (table expected, got string)

错误原因

从dump(ownedcars)的输出可知,result[i].vehicles本身就是单条车辆的完整信息表(包含vehN、vehM、totals三个字段),但代码错误地用pairs()遍历这个表。遍历后拿到的v是每个字段的具体值(比如字符串"Caracara 4x4"、数字3),而非期望的车辆对象表。当试图访问v.vehM时,Lua会把字符串当作表索引,直接触发类型错误。

修复方案

去掉嵌套的pairs()循环,直接将ownedcars作为单条车辆数据处理:

for i=1, #result, 1 do
    local ownedcars = result[i].vehicles
    menu[#menu+1] = {
        header = " Model "..ownedcars.vehM.." Name "..ownedcars.vehN.." quantity"..ownedcars.totals,
        txt = "",
    }
end

补充说明

如果后续vehicles字段需要存储多条车辆数据的数组(例如vehicles = { {vehN="xxx", ...}, {vehN="yyy", ...} }),原始的嵌套循环逻辑才适用,但需先确保result[i].vehicles是数组类型。当前数据结构下,每个vehicles都是单条数据,直接处理即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 10:50:26