lua-users home
lua-l archive

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


On Thu, Feb 27, 2014 at 12:06 PM, Steve Litt <slitt@troubleshooters.com> wrote:
> On Thu, 27 Feb 2014 07:50:57 +0200
> steve donovan <steve.j.donovan@gmail.com> wrote:
>
>> On Thu, Feb 27, 2014 at 1:57 AM, Sean Conner <sean@conman.org> wrote:
>> > You can also write Lua in a functional style (you don't get lazy
>> > evaluation, but neither do you have multiple inherentance), which I
>> > feel is worth looking into.
>>
>> Absolutely, and Javier would endorse this as well, I think. The
>> mindblowingly powerful concept of "closures" = functions + bound state
>> makes a lot of those awkward patterns very straightforward.
>
> Hi Steve,
>
> I must be missing something here, because I never thought of closures
> as mindblowingly powerful. First, maybe I have the wrong idea of what a
> closure is. I thought it was an inner function contained in an outer
> function, where the inner function is passed back as the return of the
> outer function, and the inner function can see and modify the outer
> function's local variables, but each newly returned inner function
> starts over with the vars set by the outer function, so four returned
> inner functions can operate completely independently of each other. Am
> I right so far?
>
> If so, I don't see anything closures can do that
> Perl/Python/Ruby/C++/Java objects can't do, with the outer function's
> local vars being replaced by object data elements. Or, for that matter,
> a C struct where some of the struct's elements are data and others
> are function pointers, with a C macro to add OOP syntactic sugar.
>
> Don't get me wrong: I love closures because in Lua, they're one tool
> that's useful for a huge number of situations, but I've missed how
> they're more powerful than standard objects or ordinary callback
> routines.
>
> Thanks,
>
> SteveT
>
> Steve Litt                *  http://www.troubleshooters.com/
> Troubleshooting Training  *  Human Performance
>

First class functions and lexical scoping == you have closures (is my
understanding)

It opens up huge volumes of awesomeness. Not only for "objects as
closures" but also for the factory pattern. It makes it simple to
return a function that, when called, checks to see if the current
state supports the creation of an object (that maybe needs real
hardware resources that are finite) before it initializes it. You
simply wrap the creator function, use the relevant upvalues to do your
checking, manipulate incoming ctor arguments as desired and call then
call it.

C's functions can't be nested / anonymous, so you can't use them as
flexibly as you could, otherwise.

--Andrew