Hugh Aguilar wrote:
> On Jan 14, 3:09�pm, rickman <
gnu...@gmail.com> wrote:
> > Care to clue me in as to why closures are so important?
>
> No, I wouldn't care to --- read any novice-level book on programming
> any modern language for this information.
A couple of simple closure examples in Lua.
-- A function that returns a closure.
function make_stepper()
local i = 0
return function () i = i + 1 return i end
end
function make_matrix (height, width, func)
mat = {}
for row = 1, height do
mat[row] = {}
for col = 1, width do
mat[row][col] = func(row,col)
end
end
return mat
end
function print_matrix (mat)
for _, row in ipairs(mat) do
for _, x in ipairs(row) do io.write(string.format("%3d",x)) end
print()
end
end
print_matrix( make_matrix( 5, 5, function(y,x) return y*x end ))
===>
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
print_matrix( make_matrix( 4, 5, make_stepper() ))
===>
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
-- A function that returns a closure.
function make_counter ()
local cnt = 0
return
function (arg)
if arg then
return cnt
else
cnt = cnt + 1
end
end
end
counts = {string=make_counter(), number=make_counter(), table=make_counter()}
for _, x in ipairs({1,2,3,4,5,"a","b",'c',{},{}}) do
counts[ type(x) ]()
end
for key, val in pairs( counts ) do
print( val('report') .. " " .. key .. 's' )
end
===>
5 numbers
3 strings
2 tables