Callbacks and Captured State
Lesson 20 of 48 in Coddy's Lua for C Developers course.
A portable C callback often consists of a function pointer plus a context pointer. The callback casts the context to its state type and updates that object. Lua combines behavior and captured local variables in a closure. A local captured by a nested function is an upvalue, and it remains available after the factory returns. Each invocation of the factory creates fresh local state. The examples call one counter twice, storing each result before adding them. C requires the pointed-to context to remain alive; Lua keeps reachable captured state alive automatically.
C
#include <stdio.h>
struct Counter { int n; };
struct Callback { int (*call)(void *); void *context; };
static int step(void *context) {
struct Counter *counter = context;
counter->n += 1;
return counter->n;
}
int main(void) {
struct Counter counter = {0};
struct Callback callback = {step, &counter};
int first = callback.call(callback.context);
int second = callback.call(callback.context);
printf("%d\n", first + second);
return 0;
}Lua
local function counter()
local n = 0
return function()
n = n + 1
return n
end
end
local next_value = counter()
local first = next_value()
local second = next_value()
print(first + second)Porting trap
Do not move the counter into a shared global when callers need independent counters. In C, do not return a context pointer to an expired automatic object, and sequence state-changing calls explicitly.
Challenge
EasyInput is an integer starting value and a nonnegative call count. Build a counter factory whose callback increments before returning. Call one counter count times. Return the last value, or the starting value for zero calls.
Edit app.lua. The visible locked main.lua reads stdin into a sequence of lines, calls app.run(lines), and prints its returned value with one final newline. Do not print diagnostics or change the module names. Empty input gives an empty sequence. All numeric inputs are small enough to avoid overflow.
Try it yourself
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Lua for C Developers
1First Lua Programs
Run Lua ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte PositionsRecap: Format a Receipt4Functions and Closures
Functions and ArgumentsDefaults and Options TablesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions2Values and Decisions
Absence and Table FieldsTruth and Default ValuesBranches and BoundsValues and Table IdentityRecap: Admission RulesPractice on your own: Online Lua compiler