lua-users home
lua-l archive

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


On 23/10/2012 21:11, Javier Guerra Giraldez wrote:
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.

Yes, thank you very much. I knew of such uses of closures, actually, but had not yet realised they require the variable, not the data, to be recorded with the func. In fact, I guess what is needed is that whatever deals as "state" is mutable. Thus, if it is not simple data (meaning in Lua if it's a table) we could avoid having a var, what do you think? Eg the case of a color as in your example. But in the case of counter, sure, a var is needed (if I now understand correctly). (But I still feel this breaks referential transparency, I can't count on a func to only depend on its input... maybe it's only me.)

Denis