lua-users home
lua-l archive

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


On Wed, Jun 5, 2019 at 12:14 AM Thijs Schreijer <thijs@thijsschreijer.nl> wrote:
> > On 4 Jun 2019, at 21:27, Patrick Donnelly <batrick@batbytes.com> wrote:
> >
> > On Wed, May 29, 2019 at 5:38 PM Luiz Henrique de Figueiredo
> > <lhf@tecgraf.puc-rio.br> wrote:
> >>
> >> Lua 5.4.0 (alpha-rc1) is now available for testing at
> >>        http://www.lua.org/work/lua-5.4.0-alpha-rc1.tar.gz
> >
> > \o/ toclose! (I'll echo that a more Luaish syntax would be preferred
> > but I trust the Author's judgement on this.)
> >
> > I thought I'd also share that another useful local qualifier would be
> > <static>. This would be a variable scoped as normal but is initialized
> > once when the surrounding closure is created. i.e.:
> >
> > function foo(...)
> >  local <static> cache = {}
> > end
> >
> > is syntactic sugar for:
> >
> > do
> >  local cache = {}
> >  function foo(...)
> >  end
> > end
> >
> > --
> > Patrick Donnelly
> >
>
> What happens if I do:
>
> function foo(…)
>  print(cache)
>  local <static> cache = “something”
>  cache = cache .. ”.”
> end
>
> foo()
> foo()
>
> I prefer the traditional Lua idiom because it is more explicit.

I suppose the cache variable would not be in scope at the point of
"print(cache)" which makes the "syntactic sugar" analogy weaker. This
can be caught during parsing pretty easily. The other thing to
consider is access to locals to the function by the expression
assigning to the static variable. e.g.

function foo(a)
  local <static> cache = a
end

^ That should clearly be invalid code and the compiler should complain
appropriately. OTOH, having access to upvalues to foo should be
acceptable:

local _ENV = {}
function foo(a)
  local <static> rab = _ENV.bar
end

^ OK.

-- 
Patrick Donnelly