Skip to Content
Lua Quick Start Guide
book

Lua Quick Start Guide

by Gabor Szauer
July 2018
Beginner
202 pages
5h 42m
English
Packt Publishing
Content preview from Lua Quick Start Guide

Closures

Closures capture the enclosing state of a chunk. A great example of this is having a function that returns an anonymous function. The anonymous function can see the local variables of the enclosing function. However, because the anonymous function is returned, it can outlive the existing function.

When returning an anonymous function, it creates a closure. This closure captures its enclosing state (visible chunks). This mechanism lets you access the state of the enclosing function, even though that function is no longer executing. This description may sound confusing, but the code for it is pretty straightforward:

function NextNumber()  -- local to the NextNumber function  local currentNumber = 0 return function () -- anonymous function ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Beginning Lua Programming

Beginning Lua Programming

Kurt Jung, Aaron Brown
Vim Masterclass

Vim Masterclass

Jason Cannon

Publisher Resources

ISBN: 9781789343229Supplemental Content