By returning multiple ints and passing them as multiple arguments in Lua

I have a function that takes a variable amount of int as arguments.

thisFunction(1,1,1,2,2,2,2,3,4,4,7,4,2)

this function was provided as part of the framework, and I would prefer not to change the code of the function or .lua from which it is taken. So I want a function that repeats a number for me a certain number of times, so this is less repeated. Something that could work that way and achieve what was done above

thisFunction(repeatNum(1,3),repeatNum(2,4),3,repeatNum(4,2),7,4,2)

is this possible in Lua? I even like something like this:

thisFunction(repeatNum(1,3,2,4,3,1,4,2,7,1,4,1,2,1))
+4
source share
2 answers

I think you are stuck with something next to your second proposed solution, i.e.

 thisFunction(repeatNum(1,3,2,4,3,1,4,2,7,1,4,1,2,1))

, , , . .

repeatNum . . Lua 5.1. 5.2, .

function repeatNum(...)
     local results = {}
     local n = #{...}
     for i = 1,n,2 do
       local val = select(i, ...)
       local reps = select(i+1, ...)
       for j = 1,reps do
          table.insert(results, val)
       end
     end
     return unpack(results)
end

5.2, , , , unpack table.unpack.

+3

, , , , , , , .

function repeatnum(...)
    local i = 0
    local t = {...}
    local tblO = {}
    for j,v in ipairs(t) do
        if type(v) == 'table' then
           for k = 1,v[2] do
               i = i + 1
               tblO[i] = v[1]
           end
        else
           i = i + 1
           tblO[i] = v
        end
    end
    return unpack(tblO)
end
print(repeatnum({1,3},{2,4},3,{4,2},7,4,2))
+1

All Articles