Lesson 7 of 10
Closures and function factories
- 13 min
- 6 checks
- 3 hints
- Go to task
Goal
Functions that keep their own state
Explanation
In Lua a function is a value, just like a number or a string, so you can store it in a variable, pass it to a function and return it from another function. A function you define inside another function can see that function's local variables, and it keeps them even after the outer function has finished. This is called a closure.
Closures give you the factory pattern: makeCounter() defines local count = 0 and then returns a function that increases it. Every call to the factory creates a fresh count, so each counter has its own private state that nothing outside can reach. Games build ability cooldowns this way, with each ability keeping its own last-use time.
The common mistake is putting local count = 0 outside the factory, so all the counters share a single variable. And in the cooldown, record the time only when a use is accepted; otherwise every rejected attempt makes the wait longer.
Your task
Write makeCounter(), which returns a function that gives 1, then 2, then 3 with each call. Then write makeCooldown(seconds), which returns a function use(now): if this is the first use, or at least seconds seconds have passed since the last accepted use, it records now and returns true, and otherwise it returns false. The time now arrives as an argument, and in a real game it would come from the engine's clock.
Checks
6 checks- The counter returns 1, then 2, then 3
- Each counter keeps its own state
- The first use is allowed
- Rejected before the time is up and accepted once it is
- A rejected attempt doesn't reset the timer
- Each ability has its own cooldown