Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 507
cyhiso Avatar asked Feb 26 '26 05:02

cyhiso


2 Answers

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
like image 148
Michal Kottman Avatar answered Mar 02 '26 15:03

Michal Kottman


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

return get_node_by_id(xml[i], nodeId)
like image 26
lhf Avatar answered Mar 02 '26 16:03

lhf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!