lua-users home
lua-l archive

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



On Fri, Jun 7, 2019 at 1:15 AM Egor Skriptunoff <egor.skriptunoff@gmail.com> wrote:

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

Discounting the details of translating this into normal Lua code, the first question is easy: the only consistent answer is that it would be global y, because the static y isn't in scope yet.

The second question is harder, but there are two additional options you haven't listed.

A third option that would be consistent with how it's done in C and C++: the first time foo() is called, y is initialized with a table containing the parameter passed to the function. Subsequent calls skip over the initialization (because it's already initialized) and proceed with the next line of code.

A fourth option would be that every time the line executes it overwrites the previous value of y with a table containing the parameter passed to the function. This isn't especially useful, to be fair, but it would be consistent; if this isn't the behavior you want, then you write it differently, perhaps:

local <static> y
if y == nil then 
  y = {x}
else
  -- what goes here depends on what you're trying to do
end

As I said at the beginning, the real challenge of this is in defining how it would be translated into Lua code without it. I think the best way to accomplish it would be to rename the static variable into a dedicated label at parse time. Since the Lua documentation says that identifiers starting with an underscore followed by uppercase letters are reserved, then I would suggest _STATIC_y.

The actual bytecode compiler wouldn't need this step, as it shouldn't have a problem distinguishing between the distinct upvalues.

/s/ Adam