lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Tue, Oct 23, 2012 at 1:41 PM, spir <denis.spir@gmail.com> wrote:
> Now, why people find it more useful than dangerous (that closures close on
> vars, not data), I don't know.

it's a well-known feature in language design.  you don't have to think
hard on its effects each time, just ask yourself:  "this construct
needs lexical scoping.  does this language have it? if so, i'm good"

as a simple example, it lets you have really private vars shared by a
few functions:

do
  local counter
  function inc()  counter=counter+1 end
  function get() return counter end
end

or private fields for OOP:

function new_obj()
  local color
  return {
    radius = 10,
    setparams =function (self,in_radius,in_color)
self.radius=in_radius, color=in_color end,
    draw = function (self) draw_circle (self.radius,color) end
  }
end

and lots more.  In fact, once you're used to handle closures around it
becomes the natural way to keep state around, avoiding the "function
pointer plus opaque pointer" idiom used in C for callbacks.

-- 
Javier