2

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?

2
  • 1
    This is simply impossible that it prints the content of xml[i] ok, then returns nil ... unless you've got some freaky metatable stuff going on there. I'd revise your code sample. Commented Jul 14, 2011 at 14:24
  • i know that this is unlogical))) but it is) i can't imagine whats the problem ... Commented Jul 14, 2011 at 14:27

2 Answers 2

7

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

return get_node_by_id(xml[i], nodeId)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.