lua-users home
lua-l archive

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




On Wed, Jun 5, 2019 at 9:02 PM Patrick Donnelly wrote:
> > 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
> >
>
> 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.




How the following code should be interpreted?

   local function foo(x)
      print(y)                -- is it global y or static y?
      local <static> y = {x}  -- is it global x or syntax error "local x is not accessible in static definition"?
      ...
   end