Callbacks and Captured State
Lesson 20 of 48 in Coddy's Lua for GDScript Developers course.
GDScript lambdas are Callable values invoked through call(). Local values are captured when the lambda is created, and rebinding a captured local inside the lambda does not update the original local. A common stateful pattern captures an array or dictionary and mutates that shared object instead. Lua closures capture surrounding local variables as upvalues, so the nested function can directly update a numeric counter with value = value + 1. Call the returned Lua function with ordinary parentheses. Each invocation of the factory creates a separate local counter; repeated calls to one returned function share that function's counter. Keep the initialization outside the callback body.
GDScript 4
extends SceneTree
func make_counter(start: int) -> Callable:
var state = [start]
return func():
state[0] += 1
return state[0]
func _init():
var counter = make_counter(4)
print(counter.call())
print(counter.call())
quit()Lua 5.1
local function make_counter(start)
local value = start
return function()
value = value + 1
return value
end
end
local counter = make_counter(4)
print(counter())
print(counter())Porting trap
Putting local value = start inside the returned Lua function resets the counter on every call. Initialize it in the factory's scope so the closure retains it.
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 GDScript Developers
1First Lua Programs
Run Lua ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte IndexesRecap: Format a Receipt4Functions and Closures
Functions and ReturnsDefaults and Missing ValuesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions2Values and Decisions
null and Missing FieldsTruth and Default ValuesBranches and BoundsEquality and IdentityRecap: Admission RulesPractice on your own: Online Lua compiler