Callback (computer programming): Difference between revisions

Content deleted Content added
Made the random function actually work, as the function did not set a seed value before running the example code
Added missing space.
 
(98 intermediate revisions by 59 users not shown)
Line 1:
{{Short description |A function reference passed to and called by another function}}
{{For|a discussion of callback with computer [[modem]]s|Callback (telecommunications)}}
{{For |a discussion of callback with computer [[modem]]s |Callback (telecommunications)}}
{{More references|date=September 2015}}
{{More references |date=September 2015}}
[[File:Callback-notitle.svg|thumb|370px|A callback is often back on the level of the original caller.]]
 
In [[computer programming]], a '''callback''' is [[programming pattern]] in which a [[Function (computer programming)|function]] [[reference (computer science)|reference]] is passed from one context (consumer) to another (provider) such that the provider can call the function. If the function accesses [[state (computer science)|state]] or [[function (computer programming)|functionality]] of the consumer, then the call is ''back'' to the consumer; backwards compared to the normal [[flow of control]] in which a consumer calls a provider.
In [[computer programming]], a '''callback''', also known as a "'''call-after'''"<ref>{{Cite web|url=https://stackoverflow.com/a/7549753/653708|title=What is a callback function?|website=Stack Overflow|access-date=2018-05-16}}</ref> '''function''', is any [[executable code]] that is passed as an [[argument (computer science)|argument]] to other code; that other code is expected to ''call back'' (execute) the argument at a given time. This execution may be immediate as in a '''synchronous callback''', or it might happen at a later time as in an '''asynchronous callback'''.
[[Programming languages]] support callbacks in different ways, often implementing them with [[subroutines]], [[Lambda (programming)|lambda expressions]], [[block (programming)|blocks]], or [[function pointers]].
 
A function that accepts a callback [[Parameter (computer programming)|parameter]] may be designed to call back before [[Return statement |returning]] to its caller. But, more typically, a callback reference is stored by the provider so that it can call the function later; as ''deferred''. If the provider invokes the callback on the same [[thread (computer programming)|thread]] as the consumer, then the call is ''blocking'', a.k.a. ''[[Synchronization (computer science)|synchronous]]''. If instead, the provider invokes the callback on a different thread, then the call is ''[[Non-blocking algorithm |non-blocking]]'', a.k.a. ''asynchronous''.
== {{Anchor|TYPES}}Design ==
There are two types of callbacks, differing in how they control data flow at runtime: ''blocking callbacks'' (also known as ''synchronous callbacks'' or just ''callbacks'') and ''deferred callbacks'' (also known as ''asynchronous callbacks''). While blocking callbacks are invoked before a function returns (in the C example below, which illustrates a blocking callback, it is function {{Mono|main}}), deferred callbacks may be invoked after a function returns. Deferred callbacks are often used in the context of I/O operations or event handling, and are called by interrupts or by a different thread in case of multiple threads. Due to their nature, blocking callbacks can work without interrupts or multiple threads, meaning that blocking callbacks are not commonly used for synchronization or delegating work to another thread.
 
A callback can be likened to leaving instructions with a tailor for what to do when a suit is ready, such as calling a specific phone number or delivering it to a given address. These instructions represent a callback: a function provided in advance to be executed later, often by a different part of the system and not necessarily by the one that received it.
Callbacks are used to program applications in [[Windowing system|windowing systems]]. In this case, the application supplies (a reference to) a specific custom callback function for the operating system to call, which then calls this application-specific function in response to events like mouse clicks or key presses. A major concern here is the management of privilege and security: whilst the function is called from the operating system, it should not run with the same [[Supervisor mode|privilege]] as the system. A solution to this problem is using [[Ring (computer security)|rings]] of protection.
 
The difference between a general function reference and a callback can be subtle, and some use the terms interchangeably but distinction generally depends on programming intent. If the intent is like the [[callback (telecommunications)|telephone callback]] {{endash}} that the original [[called party]] communicates back to the original [[calling party |caller]] {{endash}} then it's a callback.
==Implementation==
The form of a callback varies among [[programming language]]s:
 
== {{Anchor |TYPES}}Use ==
* In [[Assembly language|assembly]], [[C (programming language)|C]], [[C++]], [[Pascal (programming language)|Pascal]], [[Modula2]] and similar languages, a machine-level [[function pointer|pointer]] to a function may be passed as an argument to another (internal or external) function. This is supported by most compilers and provides the advantage of using different languages together without special wrapper libraries or classes. One example may be the [[Windows API]] that is directly (more or less) accessible by many different languages, compilers and assemblers.
* C++ allows objects to provide their own implementation of the function call operation. The [[Standard Template Library]] accepts these objects (called ''[[function object|functors]]''), as well as function pointers, as parameters to various polymorphic algorithms.
<!-- Please clarify before you put this back in: *Some systems have built-in programming languages to support extension and adaptation. These languages provide callbacks without the need for separate software development tools. -->
* Many [[Dynamic programming language|dynamic languages]], such as [[JavaScript]], [[Lua (programming language)|Lua]], [[Python (programming language)|Python]], [[Perl]]<ref>{{cite web |url=http://www.unix.org.ua/orelly/perl/cookbook/ch11_05.htm |title=Perl Cookbook - 11.4. Taking References to Functions|accessdate=2008-03-03}}</ref><ref>{{cite web |url=http://www.unix.org.ua/orelly/perl/advprog/ch04_02.htm |title=Advanced Perl Programming - 4.2 Using Subroutine References |accessdate=2008-03-03}}</ref> and [[PHP]], simply allow a function object to be passed through.
* [[List of CLI languages|CLI languages]] such as [[C Sharp (programming language)|C#]] and [[VB.NET]] provide a [[type safety|type-safe]] encapsulating reference, a "[[Delegate (CLI)|delegate]]", to define well-typed [[function pointer]]s. These can be used as callbacks.
* Events and [[event handlers]], as used in .NET languages, provide generalized syntax for callbacks.
* Functional languages generally support [[first-class functions]], which can be passed as callbacks to other functions, stored as data or returned from functions.
* Some languages, such as [[Algol 68]], Perl, Python, [[Ruby (programming language)|Ruby]], [[Smalltalk]], [[C++11]] and later, newer versions of C# and VB.NET as well as most functional languages, allow unnamed blocks of code ([[lambda (programming)|lambda expressions]]) to be supplied instead of references to functions defined elsewhere.
* In some languages, e.g. [[Scheme (programming language)|Scheme]], [[ML (programming language)|ML]], JavaScript, Perl, Smalltalk, PHP (since 5.3.0),<ref>{{cite web |url=https://secure.php.net/manual/en/functions.anonymous.php |title=PHP Language Reference - Anonymous functions | accessdate=2011-06-08}}</ref> C++11 and later, Java (since 8),<ref>{{cite web |url=http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html|title=What's New in JDK 8|work=oracle.com}}</ref> and many others, such functions can be [[Closure (computer science)|closures]], i.e. they can access and modify variables locally defined in the context in which the function was defined. Note that Java cannot, however, modify the local variables in the enclosing scope.
* In [[object-oriented programming]] languages without function-valued arguments, such as in [[Java (programming language)|Java]] before its 8 version, callbacks can be simulated by passing an instance of an abstract class or interface, of which the receiver will call one or more methods, while the calling end provides a concrete implementation. Such objects are effectively a bundle of callbacks, plus the data they need to manipulate{{Clarify|date=September 2014}}. They are useful in implementing various [[design patterns (computer science)|design patterns]] such as [[visitor pattern|Visitor]], [[observer pattern|Observer]], and [[strategy pattern|Strategy]].
 
A blocking callback runs in the [[Execution (computing)|execution]] context of the function that passes the callback. A deferred callback can run in a different context such as during [[interrupt]] or from a [[Thread (computing)|thread]]. As such, a deferred callback can be used for synchronization and delegating work to another thread.
==Use==
 
=== Event handling ===
 
A callback can be used for event handling. Often, consuming code registers a callback for a particular type of event. When that event occurs, the callback is called. Callbacks are often used to program the [[graphical user interface]] (GUI) of a program that runs in a [[windowing system]]. The application supplies a reference to a custom callback function for the windowing system to call. The windowing system calls this function to notify the application of events like [[computer mouse|mouse]] clicks and [[computer keyboard|key]] presses.
===C===
Callbacks have a wide variety of uses, for example in error signaling: a [[Unix]] program might not want to terminate immediately when it receives [[SIGTERM]], so to make sure that its termination is handled properly, it would register the cleanup function as a callback. Callbacks may also be used to control whether a function acts or not: [[Xlib]] allows custom predicates to be specified to determine whether a program wishes to handle an event.
 
=== Asynchronous action ===
The following [[C (programming language)|C]] code demonstrates the use of callbacks to display two numbers.
 
A callback can be used to implement asynchronous processing.
<syntaxhighlight lang="c">
#include <stdio.h>
#include <stdlib.h>
 
A caller requests an action and provides a callback to be called when the action completes which might be long after the request is made.
/* The calling function takes a single callback as a parameter. */
void PrintTwoNumbers(int (*numberSource)(void)) {
int val1 = numberSource();
int val2 = numberSource();
printf("%d and %d\n", val1, val2);
}
 
=== Polymorphism ===
/* A possible callback */
int overNineThousand(void) {
return (rand()%1000) + 9001;
}
 
A callback can be used to implement [[Polymorphism (computer science)|polymorphism]]. In the following pseudocode, {{code|say_hi}} can take either {{code|write_status}} or {{code|write_error}}.
/* Another possible callback. */
int meaningOfLife(void) {
return 42;
}
 
<syntaxhighlight lang="python">
/* Here we call PrintTwoNumbers() with three different callbacks. */
def write_status(message: str):
int main(void) {
write(stdout, message)
time_t t;
 
srand((unsigned)time(&t)); // Init seed for random function
def write_error(message: str):
PrintTwoNumbers(&rand);
write(stderr, message)
PrintTwoNumbers(&overNineThousand);
 
PrintTwoNumbers(&meaningOfLife);
def say_hi(write):
return 0;
write("Hello world")
}
</syntaxhighlight>
 
== Implementation ==
This should provide output similar to:
 
The callback technology is implemented differently by [[programming language]].
125185 and 89187225
9084 and 9441
42 and 42
 
In [[Assembly language|assembly]], [[C (programming language)|C]], [[C++]], [[Pascal (programming language)|Pascal]], [[Modula2]] and other languages, a callback function is stored internally as a [[function pointer]]. Using the same storage allows different languages to directly share callbacks without a [[program lifecycle phase|design-time or runtime]] [[interoperability]] [[Abstraction layer|layer]]. For example, the [[Windows API]] is accessible via multiple languages, compilers and assemblers.C++ also allows objects to provide an implementation of the function call operation. The [[Standard Template Library]] accepts these objects (called ''[[function object|functors]]'') as parameters.Many [[Dynamic programming language|dynamic languages]], such as [[JavaScript]], [[Lua (programming language)|Lua]], [[Python (programming language)|Python]], [[Perl]]<ref>{{cite web |url=http://www.unix.org.ua/orelly/perl/cookbook/ch11_05.htm |title=Perl Cookbook - 11.4. Taking References to Functions|date=2 July 1999 |accessdate=2008-03-03}}</ref><ref>{{cite web |url=http://www.unix.org.ua/orelly/perl/advprog/ch04_02.htm |title=Advanced Perl Programming - 4.2 Using Subroutine References |date=2 July 1999 |accessdate=2008-03-03}}</ref> and [[PHP]], allow a function object to be passed.[[List of CLI languages|CLI languages]] such as [[C Sharp (programming language)|C#]] and [[VB.NET]] provide a [[type safety|type-safe]] encapsulating function reference known as [[Delegate (CLI)|delegate]]. Events and [[event handlers]], as used in .NET languages, provide for callbacks. Functional languages generally support [[first-class functions]], which can be passed as callbacks to other functions, stored as data or returned from functions.
Note how this is different from simply passing the output of the callback function to the calling function, PrintTwoNumbers() - rather than printing the same value twice, the PrintTwoNumbers calls the callback as many times as it requires. This is one of the two main advantages of callbacks.
 
Many languages, including Perl, Python, [[Ruby (programming language)|Ruby]], [[Smalltalk]], [[C++]] (11+), C# and VB.NET (new versions) and most functional languages, support [[lambda (programming)|lambda expressions]], unnamed functions with inline syntax, that generally acts as callbacks..In some languages, including [[Scheme (programming language)|Scheme]], [[ML (programming language)|ML]], JavaScript, Perl, Python, Smalltalk, PHP (since 5.3.0),<ref>{{cite web |url=https://secure.php.net/manual/en/functions.anonymous.php |title=PHP Language Reference - Anonymous functions | accessdate=2011-06-08}}</ref> C++ (11+), Java (since 8),<ref>{{cite web |url=http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html|title=What's New in JDK 8|work=oracle.com}}</ref> and many others, a lambda can be a [[Closure (computer science)|closure]], i.e. can access variables locally defined in the context in which the lambda is defined.In an [[object-oriented programming]] language such as [[Java (programming language)|Java]] versions before function-valued arguments, the behavior of a callback can be achieved by passing an object that implements an interface. The methods of this object are callbacks.In [[PL/I]] and [[ALGOL 60]] a callback procedure may need to be able to access local variables in containing blocks, so it is called through an ''entry variable'' containing both the entry point and context information. <ref>{{cite book |editor1-last=Belzer |editor1-first=Jack |editor2-last=Holzman |editor2-first=Albert G |editor3-last=Kent |editor3-first=Allen |title=Encyclopedia of Computer Science and Technology: Volume 12 |date=1979 |publisher=Marcel Dekker, inc. |isbn=0-8247-2262-0 |page=164 |url=https://books.google.com/books?id=IFmaqTI9-KsC&pg=PA164 |access-date=January 28, 2024}}</ref>
The other advantage is that the calling function can pass whatever parameters it wishes to the called functions (not shown in the above example). This allows correct [[information hiding]]: the code that passes a callback to a calling function does not need to know the parameter values that will be passed to the function. If it only passed the return value, then the parameters would need to be exposed publicly.{{Examples|date=July 2012}}
 
==Example code==
Another example:
 
=== C ===
<syntaxhighlight lang="c">
/*
* This is a simple C program to demonstrate the usage of callbacks
* The callback function is in the same file as the calling code.
* The callback function can later be put into external library like
* e.g. a shared object to increase flexibility.
*
*/
 
Callbacks have a wide variety of uses, for example in error signaling: a [[Unix]] program might not want to terminate immediately when it receives [[SIGTERM]], so to make sure that its termination is handled properly, it would register the cleanup function as a callback. Callbacks may also be used to control whether a function acts or not: [[Xlib]] allows custom predicates to be specified to determine whether a program wishes to handle an event.In the following [[C (programming language)|C]] code, function <code>print_number</code> uses parameter <code>get_number</code> as a blocking callback. <code>print_number</code> is called with <code>get_answer_to_most_important_question</code> which acts as a callback function. When run the output is: "Value: 42".
 
<syntaxhighlight lang="c">
#include <stdio.h>
#include <stringstdlib.h>
 
void print_number(int (*get_number)(void)) {
typedef struct _MyMsg {
int appIdval = get_number();
printf("Value: %d\n", val);
char msgbody[32];
}
} MyMsg;
 
int get_answer_to_most_important_question(void) {
void myfunc(MyMsg *msg)
return 42;
{
if (strlen(msg->msgbody) > 0 )
printf("App Id = %d \nMsg = %s \n",msg->appId, msg->msgbody);
else
printf("App Id = %d \nMsg = No Msg\n",msg->appId);
}
 
int main(void) {
/*
print_number(get_answer_to_most_important_question);
* Prototype declaration
*/
void (*callback)(MyMsg *);
 
int main(void)
{
MyMsg msg1;
msg1.appId = 100;
strcpy(msg1.msgbody, "This is a test\n");
 
/*
* Assign the address of the function "myfunc" to the function
* pointer "callback" (may be also written as "callback = &myfunc;")
*/
callback = myfunc;
 
/*
* Call the function (may be also written as "(*callback)(&msg1);")
*/
callback(&msg1);
 
return 0;
}
</syntaxhighlight>
 
=== C++ ===
The output after compilation:
 
<syntaxhighlight lang="console">
$ gcc cbtest.c
$ ./a.out
App Id = 100
Msg = This is a test
</syntaxhighlight>
 
In C++, [[Function object|functor]] can be used in addition to function pointer.
This information hiding means that callbacks can be used when communicating between processes or threads, or through serialised communications and tabular data. {{Clarify|date=August 2011}}
 
=== C# ===
 
A simple callback in [[C Sharp (programming language)|C#]]:
In the following [[C Sharp (programming language)|C#]] code,
method <code>Helper.Method</code> uses parameter <code>callback</code> as a blocking callback. <code>Helper.Method</code> is called with <code>Log</code> which acts as a callback function. When run, the following is written to the console: "Callback was: Hello world".
 
<syntaxhighlight lang="c#">
public class Class1 MainClass
{
static void Main(string[] args)
{
Class2Helper c2helper = new Class2Helper();
helper.Method(Log);
/*
* Calling method on Class2 with callback method as parameter
*/
c2.Method(CallBackMethod);
}
 
static void Log(string str)
/*
* The callback method. This method prints the string sent in the callback
*/
static void CallBackMethod(string str)
{
Console.WriteLine($"Callback was: {str}");
Line 163 ⟶ 98:
}
 
public class Class2Helper
{
/*
* The method that calls back to the caller. Takes an action (method) as parameter
*/
public void Method(Action<string> callback)
{
/*callback("Hello world");
* Calls back to method CallBackMet in Class1 with the message specified
*/
callback("The message to send back");
}
}
</syntaxhighlight>
 
===JavaScript Kotlin ===
Callbacks are used in the implementation of languages such as [[JavaScript]], including support of JavaScript functions as callbacks through js-ctypes<ref>{{cite web |title=Callbacks|url=https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes/js-ctypes_reference/Callbacks|publisher=Mozilla Developer Network|accessdate=13 December 2012}}</ref> and in components such as addEventListener.<ref>{{cite web |title=Creating Javascript Callbacks in Components|url=https://developer.mozilla.org/en-US/docs/Creating_JavaScript_callbacks_in_components#JavaScript_functions_as_callbacks|publisher=Mozilla Developer Network|accessdate=13 December 2012}}</ref> However, a native example of a callback can be written without any complex code:
 
In the following [[Kotlin (programming language)|Kotlin]] code, function <code>askAndAnswer</code> uses parameter <code>getAnswer</code> as a blocking callback. <code>askAndAnswer</code> is called with <code>getAnswerToMostImportantQuestion</code> which acts as a callback function. Running this will tell the user that the answer to their question is "42".
<syntaxhighlight lang="javascript">
 
function calculate(num1, num2, callbackFunction) {
<syntaxhighlight lang="kotlin">
return callbackFunction(num1, num2);
fun main() {
print("Enter the most important question: ")
val question = readLine()
askAndAnswer(question, ::getAnswerToMostImportantQuestion)
}
 
fun getAnswerToMostImportantQuestion(): Int {
function calcProduct(num1, num2) {
return num1 * num2;42
}
 
fun askAndAnswer(question: String?, getAnswer: () -> Int) {
function calcSum(num1, num2) {
println("Question: $question")
return num1 + num2;
println("Answer: ${getAnswer()}")
}
// alerts 75, the product of 5 and 15
alert(calculate(5, 15, calcProduct));
// alerts 20, the sum of 5 and 15
alert(calculate(5, 15, calcSum));
</syntaxhighlight>
 
=== JavaScript ===
First a function {{Mono|calculate}} is defined with a parameter intended for callback: {{Mono|callbackFunction}}. Then a function that can be used as a callback to {{Mono|calculate}} is defined, {{Mono|calcProduct}}. Other functions may be used for {{Mono|callbackFunction}}, like {{Mono|calcSum}}. In this example, {{Mono|calculate()}} is invoked twice, once with {{Mono|calcProduct}} as a callback and once with {{Mono|calcSum}}. The functions return the product and sum, respectively, and then the alert will display them to the screen.
 
In the following [[JavaScript]] code, function <code>calculate</code> uses parameter <code>operate</code> as a blocking callback. <code>calculate</code> is called with <code>multiply</code> and then with <code>sum</code> which act as callback functions.
In this primitive example, the use of a callback is primarily a demonstration of principle. One could simply call the callbacks as regular functions, {{Mono|calcProduct(num1, num2)}}. Callbacks are generally used when the function needs to perform events before the callback is executed, or when the function does not (or cannot) have meaningful return values to act on, as is the case for [[Ajax (programming)|Asynchronous JavaScript]] (based on timers) or [[XMLHttpRequest]] requests. Useful examples can be found in [[JavaScript libraries]] such as [[jQuery]] where the .each() method iterates over an array-like object, the first argument being a callback that is performed on each iteration.
 
<syntaxhighlight lang="javascript">
===Red and REBOL===
function calculate(a, b, operate) {
return operate(a, b);
}
function multiply(a, b) {
return a * b;
}
function sum(a, b) {
return a + b;
}
// outputs 20
alert(calculate(10, 2, multiply));
// outputs 12
alert(calculate(10, 2, sum));
</syntaxhighlight>
 
The collection method {{code|.each()}} of the [[jQuery]] [[JavaScript libraries|library]] uses the function passed to it as a blocking callback. It calls the callback for each item of the collection. For example:
 
<syntaxhighlight lang="javascript">
$("li").each(function(index) {
console.log(index + ": " + $(this).text());
});
</syntaxhighlight>
 
Deferred callbacks are commonly used for handling events from the user, the client and timers. Examples can be found in {{code|addEventListener}}, [[Ajax (programming)|Ajax]] and <code>[[XMLHttpRequest]]</code>.
<ref>{{cite web |url=https://udn.realityripple.com/docs/Mozilla/Creating_JavaScript_callbacks_in_components#JavaScript_functions_as_callbacks |title=Creating JavaScript callbacks in components |department=Archive |website=UDN Web Docs |at=sec. JavaScript functions as callbacks |language=en |type=Documentation page |accessdate=2021-12-16 |url-status=live|archive-url=https://web.archive.org/web/20211216020616/https://udn.realityripple.com/docs/Mozilla/Creating_JavaScript_callbacks_in_components |archive-date=2021-12-16 }}</ref>
 
In addition to using callbacks in JavaScript source code, C functions that take a function are supported via js-ctypes.<ref>{{cite web |url=https://developer.mozilla.org.cach3.com/en-US/docs/Mozilla/js-ctypes/Using_js-ctypes/Declaring_and_Using_Callbacks<!--This page is not properly rendered--> |title=Declaring and Using Callbacks |editor1-last=Holley |editor1-first=Bobby |editor2-last=Shepherd |editor2-first=Eric |department=Docs |website=[[Mozilla Developer Network]] |language=en |type=Documentation page |accessdate=2021-12-16 |url-status=live |archive-url=https://web.archive.org/web/20190117092921/https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes/Using_js-ctypes/Declaring_and_Using_Callbacks |archive-date=2019-01-17}}</ref>
 
=== Red and REBOL ===
 
FromThe the [[JavaScript]] above, here is how one would implement the same in eitherfollowing [[REBOL]] or /[[Red (programming language)|Red]]. Noticecode thedemonstrates cleanercallback presentation of data as codeuse.
 
* return is implied as the code in each function is the last line of the block
* As alert requires a string, form produces a string from the result of calculate
* The get-word! values (i.e., :calc-product and :calc-sum) trigger the interpreter to return the code of the function rather than evaluate with the function.
Line 242 ⟶ 199:
; alerts 20, the sum of 5 and 15
alert form calculate 5 15 :calc-sum
</syntaxhighlight>
 
=== Rust ===
[[Rust (programming language)|Rust]] have the {{Code|Fn}}, {{Code|FnMut}} and {{Code|FnOnce}} traits.<ref>{{cite web |title=Fn in std::ops - Rust |url=https://doc.rust-lang.org/std/ops/trait.Fn.html |website=doc.rust-lang.org |access-date=18 January 2025}}</ref>
 
<syntaxhighlight lang="rust">
fn call_with_one<F>(func: F) -> usize
where F: Fn(usize) -> usize {
func(1)
}
 
let double = |x| x * 2;
assert_eq!(call_with_one(double), 2);
</syntaxhighlight>
 
===Lua===
In this [[Lua]] code, function {{code|calculate}} accepts the {{code|operation}} parameter which is used as a blocking callback. {{code|calculate}} is called with both {{code|add}} and {{code|multiply}}, and then uses an [[anonymous function]] to divide.
A color tweening example using the [[Roblox]] engine that takes an optional .done callback:
 
<syntaxhighlight lang="lua">function calculate(a, b, operation)
return operation(a, b)
wait(1)
end
local DT = wait()
 
function tween_colormultiply(objecta, finish_color, fade_timeb)
return a * b
local step_r = finish_color.r - object.BackgroundColor3.r
local step_g = finish_color.g - object.BackgroundColor3.g
local step_b = finish_color.b - object.BackgroundColor3.b
local total_steps = 1/(DT*(1/fade_time))
local completed;
coroutine.wrap(function()
for i = 0, 1, DT*(1 / fade_time) do
object.BackgroundColor3 = Color3.new (
object.BackgroundColor3.r + (step_r/total_steps),
object.BackgroundColor3.g + (step_g/total_steps),
object.BackgroundColor3.b + (step_b/total_steps)
)
wait()
end
if completed then
completed()
end
end)()
return {
done = function(callback)
completed = callback
end
}
end
 
function add(a, b)
tween_color(some_object, Color3.new(1, 0, 0), 1).done(function()
return a + b
print "Color tweening finished!"
end)
 
print(calculate(10, 20, multiply)) -- outputs 200
print(calculate(10, 20, add)) -- outputs 30
-- an example of a callback using an anonymous function
print(calculate(10, 20, function(a, b)
return a / b -- outputs 0.5
end))</syntaxhighlight>
 
=== Python ===
 
In the following [[Python (programming language)|Python]] code, function {{code|calculate}} accepts a parameter {{code|operate}} that is used as a blocking callback. {{code|calculate}} is called with {{code|square}} which acts as a callback function.
 
<syntaxhighlight lang="python">
def square(val):
return val ** 2
 
def calculate(operate, val):
return operate(val)
 
calculate(square, 5) # outputs: 25
</syntaxhighlight>
 
===PythonJulia===
A classic use of callbacks in Python (and other languages) is to assign events to UI elements.
 
In the following [[Julia (programming language)|Julia]] code, function {{code|calculate}} accepts a parameter {{code|operate}} that is used as a blocking callback. {{code|calculate}} is called with {{code|square}} which acts as a callback function.
Here is a very trivial example of the use of a callback in Python. First define two functions, the callback and the calling code,
then pass the callback function into the calling code.
 
<syntaxhighlight lang="pyconjlcon">
>>julia> def get_squaresquare(val): = val^2
square (generic function with 1 method)
... """The callback."""
julia> calculate(operate, val) = operate(val)
... return val ** 2
calculate (generic function with 1 method)
...
julia> calculate(square, 5)
>>> def caller(func, val):
... return func(val)
...
>>> caller(get_square, 5)
25
</syntaxhighlight>
Line 319 ⟶ 282:
 
== External links ==
* [https://web.archive.org/web/20071009224137/http://msdnlearn.microsoft.com/msdnmagen-us/issuesarchive/02msdn-magazine/122002/BasicInstinctsdecember/using-net-implementing-callback-notifications-using-delegates Basic Instincts: Implementing Callback Notifications Using Delegates] - [[MSDN Magazine]], December 2002
* [https://web.archive.org/web/20080916192721/http://www.javaworld.com/javaworld/javatips/jw-javatip10.html Implement callback routines in Java]
* [https://web.archive.org/web/20041111063702/http://www.codeproject.com/aspnetArticles/ScriptCallbackFramework.asp7865/Implement-Script-Callback-Framework-in-ASP-NET-1-x Implement Script Callback Framework in ASP.NET 1.x] - Code Project, 2 August 2004
* [https://web.archive.org/web/20110706132209/http://www.comp.ua.ac.be/publications/files/Adapter-Para04.pdf Interfacing C++ member functions with C libraries] (archived from the original on July 6, 2011)
* [http://gotw.ca/gotw/083.htm Style Case Study #2: Generic Callbacks]
 
[[Category:Articles with example C code]]
[[Category:Articles with example C++ code]]
[[Category:Articles with example C Sharp code]]
[[Category:Articles with example JavaScript code]]
[[Category:Articles with example Julia code]]
[[Category:Articles with example Python (programming language) code]]
[[Category:Articles with example Rust code]]
[[Category:Subroutines]]