cyhiso
cyhiso

Reputation: 57

Lua return from function problem

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?

Upvotes: 2

Views: 1690

Answers (2)

Michal Kottman
Michal Kottman

Reputation: 16753

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

Upvotes: 7

lhf
lhf

Reputation: 72312

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

return get_node_by_id(xml[i], nodeId)

Upvotes: 2

Related Questions