Merge function in Lua
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
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.
上一篇: b而a&b是数组或表格
下一篇: 合并函数在Lua中