I currently have been trying to understand certain things through the Documentation, but many of the pages mention “callbacks”
What exactly is a callback? What does it do? Is it important(
I currently have been trying to understand certain things through the Documentation, but many of the pages mention “callbacks”
What exactly is a callback? What does it do? Is it important(
Its data that is supposed to be used by other data, heres a basic chart:
Here the main program calls a function, but in that function, calls another function, heres a basic code example:
function ReturnRandom()
return math.random(1, 20)
end
function GetResultAndMultiply(MultiplicationNum)
local ReturnedNum = ReturnRandom()
local Answer = ReturnedNum * MultiplicationNum
return Answer
end
function PrintAnswer()
local Answer = GetResultAndMultiply(5)
print(Answer)
end
PrintAnswer()
Here we have a 3 step process, we get a random number from the ReturnRandom
function, The GetResultAndMultiply
function gets that number and multiplies it, and then we call that function in the PrintAnswer
function and print it.
This is just a basic example, and not the best, but that’s basically what a callback is, the GetResultAndMultiply
and the ReturnRandom
functions are the callback functions, heres a wikipedia explanation:
I think I understand it a little better.
If I had a function and connected it to a remotevent that fires when a part is Touched, if i have that function call another function, that called function would be a callback?
In other words, a callback function is a function that is designed to be called by another function…
Nothing else?
Yep, that is correct.
the30isthelimit
Yup. Furthermore all connections to events are callbacks. Since you are registering a function to be called when event happens.
I think that callback function are functions that are passed as an argument to other functions to get executed after a specific event (not 100% sure)
example
function functionExecuteRepeat(interval :number, func : () -> ())
task.spawn(function()
while true do
func()
task.wait(interval)
end
end)
end
local function print5()
print(5)
end
functionExecuteRepeat(2, print5) -- print5 will get executed every 2 seconds
and you can also pass arguments to the passed callback function
function iterateTableOfNumbers(tbl : {number}, func : (number) -> ())
for _, number in tbl do
func(number) -- passes number as an argument to the function
end
end
function printNumberPow2(num)
print(num^2)
end
local tableOfNumbers = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}
iterateTableOfNumbers(tableOfNumbers, printNumberPow2)
Wow, that was suprisingly simple. Thanks for the help
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.