[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Another example for syntactically lightweight closures
- From: Eike Decker <eike@...>
- Date: Thu, 7 Feb 2008 09:22:08 +0100
Zitat von David Manura <dm.lua@math2.org>:
> Miles Bader writes:
> > Bret Victor writes:
> > > I thing I like about Lua syntax is that punctuation is kept minimal,
> > > and words are used (in, do, end) when that's how you would read the
> > > code out loud.
> >
> > I agree, in general -- I don't dislike punctuation heavy languages like
> > C, but Lua has a consistent and attractive style of its own. [Still, in
> > the middle of an expression, I think a punctuation-oriented lambda
> > syntax isn't out of place, even in Lua.]
>
> In Lua, we do write "{1,2}" rather than "table 1, 2 end". Given that
> functions
> are fundamental data type, like tables, there is consistency in using
> punctuation to denote functions, particularly when used as lambda
> expressions.
>
> Approaches for syntactically lightweight closures are also discussed in [1].
>
> [1] http://lua-users.org/wiki/ShortAnonymousFunctions
>
>
>
However we use the keywords "then", "end", "do", "and/or/not", where C or some
other languages are using special characters like |,?,~,&,$,!,@. I came from
C/Java/PHP when I learned Lua 4 years ago and wondered why using so many
written out words where a single character could be sufficient. Nevertheless I
prefer lua's way today. Of course we could use these unused characters for
describing a function, maybe like
x,y @ { $dx,dy = x-px,y-py << dx*dx+dy*dy }
instead of
function (x,y) local dx,dy = x-px,y-py return dx*dx+dy*dy end
But it introduces some weird ascii magic that has previously been avoided in
lua...
Nevertheless I tried to write a string transformer that converts the given
string from above into lua's form:
-- declare a function very shorthand:
-- parameters @ |upvalues| {code << return expression}
function sfn (str)
-- code comments and strings would be needed to be filtered since
-- these could contain some of our special chars
code = "return function ()\n"..(str:match "@%s*|(.-)|%s*{" or "") :
gsub("%$"," local ").."\n return function ("
code = code .. str:match "^(.-)@" .. ")\n"
local incode = str:match "|?%s*{(.*)}"
incode = incode : gsub("%$"," local ") : gsub("<<", " return ")
code = code ..incode.. "\nend end"
--print(code)
return assert(loadstring(code,str)) () ()
end
fn = sfn "x,y @ {$dx,dy = x-px,y-py; << dx*dx+dy*dy}"
counter = sfn "@ | $cnt = 0 | {cnt = cnt + 1 << cnt}"
px,py = 5,5
print(fn(0,0)) -- 50
print(counter()) -- 1
print(counter()) -- 2