I have a custom table class QuickList (Check it out.) and was wondering if it is better to simply merge/join the tables themselves or add each individual thing inside the tables.
Merging:
local table1 = ql{'hello', 'world'}
local table2 = ql{'foo', 'bar'}
print(table1 + table2) -- returns ql{'hello', 'world', 'foo', 'bar'}
or
Adding separately
local table1 = ql{1,2,3}
local table2 = ql{3,4}
print(table1 + table2) -- returns ql{4,6,3}
Or suggest something else because I want more people to use QuickList And go use it yourself because it can be implemented for any table use you already have (arrays only though).
Currently I’m going with the second option but I want people’s opinions since not every array is made using numbers and + or __add is very common.
I want to make it as seemless as possible and squeeze as much functionality as possible.
Read the Quicklist forum post for more detail and how to use it though.
function ql.__add(self, other)
local copy = self.copy()
copy.enumerate(function(i,v)
if #other < i then return end
copy[i] = v + other[i]
end)
return copy
end
Adding two tables together like this: {1, 2, 3} + {4, 5} = {5, 7, 3} should be its own separate function. But for appending tables: {1, 2, 3} + {4, 5} = {1, 2, 3, 4, 5} it should take precedence when you add two tables together since it works as it should.
Yeah there’s already a merge(table) function that does the joining of 2 tables. So I would assume this should take precedence.
But in lua you can’t add strings, or do anything else. And that is something that I’m wondering about.
Should I join a string and the value if you add it AND add the numbers too?
e.g {"hello", 2} + {2,2} will give {"hello2", 4}
I would recommend just making it a function, because of how complicated it can be. Should numbers be added together while strings should be joined? Or numbers should also be joined together? Such as {3} + {2} = {32}? All this complicated networking can lead to issues in the long run if you used it for the additive symbol.
Well lua doesn’t let you call __add on different data types. Which is annoying for some, as I have experience in python and adding strings works just like using the .. operator in lua. But adding numbers actually adds them.
I was thinking 3:number + 2:number = 5:number "3":string + "2":string = "32":string
Hey! Turns out there’s a __concat(a,b) metamethod. I’ll use this just to run copy[i] = v..other[i] so it just concats everything in the table with everything in the other table.
If other is a string then it concats with the string instead of each value in the table.
local tab1 = _{'hello','world'}
local tab2 = _{'foo','bar'}
print(tab1 .. tab2) -- prints {hellofoo, worldbar}
local tab1 = _{'hello','world'}
local other = "foo"
print(tab1 .. other) -- prints {hellofoo, worldfoo}