开发者

Lua return from function problem

I'm trying 开发者_如何学JAVAto 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?


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):

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
            local node = get_node_by_id(xml[i], nodeId)
            if node then return node end
        end
    end
end


I think you're missing a return in the else block:

return get_node_by_id(xml[i], nodeId)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜