Suppose I have a function that takes, say, 3 parameters as in sum() below. Now, I want to pass sum() to another function, run(). How exactly do I set this up in Lua? Here’s what I’m trying to do:
local function sum( a, b, c )
return a+b+c
end
local function run( sum ? )
local n = sum( ? )
return n
end
I do not believe this to be a varargs question because I will always know the exact number of arguments in the function to be passed.
The motivation behind this question arises from the coroutine.create() function. This function takes a single argument, a function. I want to pass a function to coroutine.create() that takes, say, 1 argument. For example,
local function f( arg1 )
... do stuff
return something
end
local co = coroutine.create( f )
Thanks,
local function sum( a, b, c )
return a+b+c
end
local function run(f, ...)
local n = f(...)
return n
end
SLASH_XXX1 = "/xx"
function SlashCmdList.XXX(msg)
print(run(sum, 4, 7, 9))
end
You could change the … in run for 3 parameters but I’m not sure if this is what you are looking for over calling sum() directly.
What are you trying to achieve?
The coroutines parameters are passed in the resume (created coroutes start in a suspended state):
local function sum( a, b, c )
return a+b+c
end
local function run(a, b, c )
local n = sum( a, b, c )
return n
end
local c = coroutine.create(run)
print(coroutine.resume(c,1,2,3))
Incidentally, lua supports closures too which can be convenient at times:
local function sum( a, b, c )
return a+b+c
end
local function total(a,b,c)
local function run()
local n = sum( a, b, c )
return n
end
return run()
end
print(total(1,2,3))