lua-users home
lua-l archive

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


On Tue, Jul 23, 2019 at 11:10 AM Viacheslav Usov <via.usov@gmail.com> wrote:
Ultimately, Lua has its own problem where one cannot write
local x = foo(), y = bar(x)

 Of course you can rewrite it as:
  local x,y; x = foo(); y = bar(x)
It's not strictly equivalent because it first declares the variables x,y and initialize them to nil, before assigning them (a smart compiler may detect that and fix the nil initializer) preventing these declarations to be marked as read-only.
But the only safe way is:
  local x = foo(); local y = bar(x)

Except that the second declaration now depends on the modified scope for "x". It is not clear in your statement:
  local x = foo(), y = bar(x)
which value of x will be passed to call "bar(x)":
* (1) the value coming for the "foo()" initializer
* (2) or the value of "x" before the whole declaration ?

For the case (1), using two separate "local" statements is the solution

For the case (2) we don't have any clean Lua syntax to provide it, except (possibly) by changing the declaration order (which may have side effects when the initializers must be evaluated in a specified order). The work around is to use an anonymous function to evaluate all initializers at once:
  local x,y= (function() begin
      return foo(), bar(x) -- note that "x" does not refer to the "local x" which is still not visible
    end)()
But it is very verbose and possibly costly (unless the compiler is tuned and inlines these inline anonymous function calls); however these "local x,y" declarations can then be augmented with annotations to make them "constant" (readonly).