Varargs Question - Passing "..." to other functions

I am having trouble understanding the correct way to pass a variable argument list to another function. A real world example would be a writing a wrapper routine that passes arguments to a coroutine executing a function that takes a variable argument list. Something like this…

local function foo( ... )
   -- do stuff
end

Setup a coroutine to execute foo(), but wrap the coroutine with a wrapper function, say, wrapper()

local function wrapper( co, ... )
         local co = coroutine.create( foo  )
         coroutine.resume( co, ... )
end

Any help would be appreciated. Thanks

Lua supports closures. You can do:

local function foo(...)
  -- do stuff
end
local function wrapper(...)
  local co = coroutine.create(function()
    foo(...)
  end)
  coroutine.resume(co)
end

Thanks, Gello, but no joy. Here’s my test code followed by the error string lua generates when trying to execute the code:

local function printStr( ... )
    local s1, s2, s3 = ...
    print( sprintf("%s, %s, %s\n", s1, s2, s3 ))
end

local function wrapper( ... )
    local co = coroutine.create( function()
        printStr(...)  --   <<<<< this is line 31
    end)

    coroutine.resume(co)
end

CoroutineTests.lua:31: cannot use '...' outside a vararg function near '...'

This is how I invoke the wrapper() function:

    local s1 = "Hello"
    local s2 = "GoodBye"
    local s3 = "How are you?"

    wrapper( s1, s2, s3 )

Thanks man!

local function printStr( ... )
    print("B", ... )
end

local function wrapper( ... )
    local co = coroutine.create( function( ...)
        printStr( ...)
    end)
    coroutine.resume(co, ...)
end

wrapper("a", 2, 3, 4)

or:

local function printStr( ... )
    print("B", ... )
end

local function wrapper( ... )
    local co = coroutine.create( printStr)
    coroutine.resume(co, ...)
end

wrapper("a", 2, 3, 4)

1 Like