I have a piece of code that will return a number of animations. I want to return them at once, using this method:
local number1 = 4
local number2 = 29
local number3 = 9
return number1, number2, number3
However, I have a table that contains those items. I want to return every single one of them. Each table might have a different length, so I can’t just do
local tbl = {4,21,9}
return tbl[1], tbl[2], tbl[3] -- works
local tbl = {4,21,9,10}
return tbl[1], tbl[2], tbl[3] -- the last one doesn't return unless I manually add in "tbl[4]"
How can I change the number of returned items based on the length of the table?
Edit: I know I can just return the entire table, but what if I don’t want to? Is there another wa?
You could do this although it would just put the values you wanted into a new table:
local tbl = {4,21,9,10}
local wantedValues = {}
for i, Value in tbl do
table.insert(wantedValues, tbl[i])
end
print(wantedValues)
Also, you can get the number of values in a table by doing: #tbl - In this case, this would be equal to 4. Idk if that’ll be helpful or not. I’m stuck too now, as If you want to return them it makes things a whole lot more complicated because as you said, return stops the function.
This isn’t scaleable? Idk how unpack() works though so I could be mistaken.
-- // a way
local t = {4, 21, 9, 10}
return table.unpack(t, #t)
-- // another way
local t = {4, 21, 9, 10}
local function unpackAll(t, prev)
local index, value = next(t, prev)
if not (index and value ~= nil) then
return
end
return value, unpackAll(t, index)
end
return unpackAll(t)
-- // another way
local t = {4, 21, 9, 10}
local function unpackSelected(t, index, ...)
if (index == nil) then
return
end
local value = t[index]
if (value == nil) then
return
end
return value, unpackSelected(t, ...)
end
return unpackSelected(t, 1, 2, 4) -- returning indices 1, 2 and 4
My bad I didn’t explain. Unpack returns a number of arguments from the table you pass with. For example you can easily clone tables using unpack like this.
local t={1,2,3,4,5}
print(t) -- [1] = 1, [2] = 2... and so on until 5
local t2 = {unpack(t)}
print(t2) -- [1] = 1, [2] = 2... and so on until 5
If you wanted it to be scaleable and assign variables. Just have a table and assign indexes.