Wednesday, January 16, 2008

Upvalues

From Beginning Lua Programming:

"When a function uses a variable that is local to a containing scope ... that variable is called an external local variable or an upvalue. ... A function that has one or more upvalues is called a closure." In the following code N is an upvalue.

> function MakeLessThan(N)
>> return function (X)
>> return X < N
>> end
> end

> LessThanFive = MakeLessThan(5)
> print (LessThanFive(4))
true

You can also call a function directly, without giving it a name.
> print (MakeLessThan(5) (4))
true

1 comment:

Methedras said...

"A local value used by an inner function is called an upvalue." Still trying to understand this concept.