tags:

views:

108

answers:

1

Hey, I'm trying to implement the merge function from merge sort in Lua. I know the algorithm pretty well, but I'm new to Lua. I keep getting a "bad argument #1 to 'insert' (table expected, got nil)" I believe the error is pointing at my recursive call. I can't figure it out and I have a feeling it's something pretty trivial. I just need a Lua guru to give me some guidance. Thanks. Here's my function:

function merge(l1, l2)
if # l1 == 0 then
    return l2
elseif # l2 == 0    then
    return l1
else
    if l1[1] <= l2[1] then
        tmp = l1[1]
        table.remove(l1,1)
        return table.insert(merge(l1,l2),tmp)

    else 
        tmp = l2[1]
        table.remove(l2,1)
        return table.insert(merge(l1,l2),tmp)
    end
end
end
+5  A: 

I am not completely sure what you want to achieve with the merge function, but a clear problem is that table.insert doesn't return a table, it returns nil.

Storing the result of the merge in table t, using table.insert on t and finally returning t doesn't seem to break as before.

function merge(l1, l2) 
    if #l1 == 0 then
        return l2
    elseif # l2 == 0 then
        return l1
    else
        if l1[1] <= l2[1] then
            local tmp = table.remove(l1, 1)
            local t = merge(l1, l2) 
            table.insert(t, tmp)
            return t
        else 
            local tmp = table.remove(l2, 1)
            local t = merge(l1, l2) 
            table.insert(t, tmp)
            return t
        end 
    end 
end

A note on the few other modifications I did. table.remove returns the removed element, so you don't have to first access the element and then remove it. I recommend using the keyword local for variables, because in Lua all variables are global by default.

ponzao
Hey. Thanks for the tips! It worked great! The merge function takes two already sorted tables and merges them into one sorted table. I had to change the table.insert(t, tmp) to table.insert(t, 1, tmp) so that it would insert the item at the beginning of the return table.
Mike K
Glad to be of help!
ponzao
Mike K, I think you forgot to mark ponzao's answer as correct.
egarcia