I’m trying to make a function that runs a different function using parameters depending on certain conditions. I know that I can do this with a function without parameters, but I want to be able to do this with a function with parameters. Is this possible? If not, what is a different method that could work?
Is this what you mean?
local function returnsNumber()
return 2
end
local function printNumber(a)
print(a)
end
printNumber(returnsNumber())
You mean something like this?
function executeFunction(func, arg1, arg2)
return func(arg1, arg2)
end
function addNumbers(x, y)
return x + y
end
local result = executeFunction(addNumbers, 5, 3)
print(result)
printNumber(returnsNumber)* is the correct way to call the function, it will error because of the parentheses
I’m thinking of something like this, but if you change the amount of arguments in the table, the amount of arguments in the function called by the execute function will respond accordingly.
local args = {
arg1 = 5,
arg2 = 6,
arg3 = 10
}
function add(num1,num2,num3)
print(num3+num1+num2)
end
function Executefunc(fuc,args)
fuc(args.arg1,args.arg2,args.arg3)
end
Executefunc(add,args)
Try this
local args = {
arg1 = 5,
arg2 = 6,
arg3 = 10
}
function add(num1, num2, num3)
print(num3 + num1 + num2)
end
function Executefunc(func, args)
func(unpack(args))
end
Executefunc(add, args)
Nope. Didn’t work. I appreciate the suggestion tho.
Try this
local args = {
[1] = 5,
[2] = 6,
[3] = 10
}
function add(...)
local args = unpack({...})
local sum = 0
for i = 1, #args do
sum += args[i]
end
return sum
end
function Executefunc(func, args)
print(func(args))
end
Executefunc(add, args)
Your solution worked! Although this seems to only work with the example that I provided, and it wouldn’t work with the function I had in mind (at least I don’t think so since I don’t really know what you did lol), you still found a solution so thank you!
Yeah thats what I was gonna say, like since your problem is kinda of more advance your going to need to probably do your own logic for it depending on what your doing, glad it worked for you though, good luck!
Do you need to pass the function as an argument? Or can you just fire the function from inside the function.
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.