lua-users home
lua-l archive

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


It seems that changing the behaviour of function definitions could
cause problems.
I propose adding some sort of new keyword to use for inlined
functions, like the lambda in Haskell. It wouldn't be allowed to use
setfenv/getfenv and there would only exist instance of each such
definition. That would fit well with how you'd want to define
table.sort comparison functions.
The same example as below with some new syntax:
table.sort(t, \a,b(a[1] < b[1]))

The following would hold:
local t = {}
for i = 1, 2 do
t[i] = \x(x*x)
end
assert(t[1] == t[2])
This would of course be different than how functions work.

This source code would be compiled down to this equivalent:
local f = function(x) return x * x end
local t = {}
for i = 1, 2 do
t[i] = f
end
assert(t[1] == t[2])


2007/9/6, Evan DeMond <evan.demond@gmail.com>:
> Sorry, to clarify my point - that is to say that creation of a new closure
> here seems like a reasonable behavior to me, and it's what I would have
> expected.
>
>
> On 9/6/07, Evan DeMond <evan.demond@gmail.com> wrote:
> >
> > On 9/6/07, Thomas Harning Jr. <harningt@gmail.com > wrote:
> >
> > > On 9/6/07, Roberto Ierusalimschy <roberto@inf.puc-rio.br> wrote:
> > > > > I'm curious about a problem I encountered with this:
> > > > >
> > > > > table.sort (sometable, function(a, b) return a[1] < b[1] end);
> > > > >
> > > > > If this is executed repeatedly this creates a new closure every
> time.
> > > > > Because, as I understand it, this function is compiled as a
> prototype
> > > > > with no upvalues, why is a new closure created every time? Seems
> > > > > unnecessary, let alone inefficient. Would it not be possible for the
> > > > > lua compiler to just get the reference to the function (closure) and
> > > > > pass it?
> > > >
> > > > Unfortunately not :(  The compiler has no way to know whether the
> > > > closure is "escaping" through 'table.sort' (e.g., being stored in
> > > > global variables), and each new closure may have its own independent
> > > > environment.
> > > >
> > > To clarify... someone could do a setfenv on the function causing its
> > > environment to be different, even though there's no upvalues.  Even if
> > > the function/closure itself doesn't touch the environment, it can
> > > still be used by external functions.  Perhaps a method to mark a
> > > function as being 'locked' and disable changing its environment or
> > > using upvalues could be an option...  However that is probably much
> > > more work than its worth...
> > >
> > > --
> > > Thomas Harning Jr.
> > >
> >
> >
> > Unless I'm missing the point, wouldn't the simple solution here be just to
> use a named comparison function, bound earlier - resulting in the creation
> of only one closure - rather than an anonymous one?
> >
>
>