Lua函数返回问题
我正在尝试用 lua 解析一些 xml 文件 我被这个函数困住了:
function get_node_by_id (xml, nodeId)
for i=1, #xml, 1 do
if get_attr_by_name(xml[i], 'Id') == nodeId then
print ("TRUEEEEE", i, xml[i])
return xml[i]
else
get_node_by_id(xml[i], nodeId)
end
end
end
问题是 print("TRUEEEEE", i, xml[i])
可以工作,但它在下一行返回 nil
<代码>返回xml[i]。 我做错了什么?
I'm trying to parse some xml files with lua and
I'm stuck on this function:
function get_node_by_id (xml, nodeId)
for i=1, #xml, 1 do
if get_attr_by_name(xml[i], 'Id') == nodeId then
print ("TRUEEEEE", i, xml[i])
return xml[i]
else
get_node_by_id(xml[i], nodeId)
end
end
end
The problem is that print("TRUEEEEE", i, xml[i])
works, but it returns nil
in the next line return xml[i]
.
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在递归地调用该函数,但仅提供单个返回。如果您碰巧在第二级中找到了要查找的节点,则仅将值返回到第一级,而第一级不会对其执行任何操作。
也许你想要这样的东西(未经测试的代码):
You are calling the function recursively, but only provide a single return. If you happen to find the node you are looking for in second level, you only return the value to first level, which doesn't do anything with it.
Maybe you want something like this (untested code):
我认为您在 else 块中缺少返回:
I think you're missing a return in the else block: