The concept of closure in Lua

Moho allows users to write new tools and plugins. Discuss scripting ideas and problems here.

Moderators: Víctor Paredes, Belgarath, slowtiger

Post Reply
User avatar
Rasheed
Posts: 2008
Joined: Tue May 17, 2005 8:30 am
Location: The Netherlands

The concept of closure in Lua

Post by Rasheed »

I had a hard time understanding the concept of closure. The concept is explained in chapter 6.1 of Programming in Lua, but, still, it is rather abstract.

In short, a closure is a function with it's environment. See this piece of code:

Code: Select all

do
  local x = 0
  function f () return x end
  function g (a) if a ~= nil then x = a end; return x end
end
-- at this point x is no longer valid
print(f() )  -- returns 0
print(g(5) ) -- returns 5
print(f() )  -- returns 5
x = 0
print(f() )  -- returns 5
print(x)     -- returns 0
I've explained this in more detail in my blog:

Anime Studio Lua Scripting: Closure - 3

A closure somewhat resembles an object (as in object oriented programming), though they are two completely different concepts. You tell a closure what it should do (functional programming), and you tell an object how it should do it (imperative programming).

What is the practical use for Anime Studio and Lua scripting? I wish I knew, because I got stuck at chapter 6.1 of Programming in Lua.
Post Reply