I'm creating an Array class that adds more usage to tables. I have a metamethod that allows me to combine two tables, ex:
Array(5) .. Array(6, 10) should give you {5, 6, 10}
I'm aware that I can use two loops to do this, but I'm trying to make my code as clean and efficient as possible. I ran into an issue with unpack. I'm trying to concatenate two tables, but it's not including all of the values. Here is my code and output:
local Array = {}
Array.__index = Array
function Array.__concat(self, other)
return Array.new(unpack(self), unpack(other))
end
function Array:concat(pattern)
return table.concat(self, pattern)
end
function Array.new(...)
return setmetatable({...}, Array)
end
setmetatable(Array, {__call = function(_, ...) return Array.new(...) end})
local x = Array(5, 12, 13) .. Array(6, 9) --concatenate two arrays
print(x:concat(", "))
OUTPUT: 5, 6, 9 (I want it to be "5, 12, 13, 6, 9")
This is standard Lua behavior: in an enumeration of function calls separated by commas, only the last one can return multiple results. For instance:
> function f() return 1, 2, 3 end
> print(f(), f())
1 1 2 3
If I were you I would do the simple thing and use a for
loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With