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

Lua中根据变量访问指定路由表返回nil的问题排查

Lua路由表访问返回nil的解决方法

你的代码返回nil主要有两个原因:

  • 未指定数组索引:routes[route]对应的是eastCityRoute或westCityRoute,这两个都是数组结构的表,必须指定具体的索引(比如1、2、3)才能定位到包含name字段的子表。
  • name引用错误:代码里的name是未定义的全局变量,Lua会将其视为nil,导致索引无效。访问表字段时,要么用.操作符直接调用字段名,要么用字符串形式的键("name")。

修正后的示例代码

route = 1

local eastCityRoute = {
    {name = "ecr-stop1"},
    {name = "ecr-stop2"},
    {name = "ecr-stop3"},
}

local westCityRoute = {
    {name = "wcr-stop1"},
    {name = "wcr-stop2"},
    {name = "wcr-stop3"},
}

routes = {}
routes[1] = eastCityRoute
routes[2] = westCityRoute

-- 访问选中路由的第一个站点名称
print(routes[route][1].name)
-- 等价写法
print(routes[route][1]["name"])

遍历所有站点的写法

如果需要输出选中路由的所有站点名称,可以用循环遍历:

for _, stop in ipairs(routes[route]) do
    print(stop.name)
end

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:40:32