lua-users home
lua-l archive

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


вт, 16 июл. 2019 г. в 08:31, pocomane <pocomane_7a@pocomane.com>:
>
> However, you can simplify scope() a bit [1], allowing to write
>
> for finally_close in scope() do
>   local file, err = io.open("myfile", "r")
>   finally_close( file )
>   -- ...
> end
>
> That is clean enough to not make me miss <toclose>. I can also ignore the fact that the 4th iterator parameter itself is implementated as a <toclose> variable.
Yes. This hides this inconsistent syntax.

// lparser.c
static void localstat (LexState *ls) {
  /* stat -> LOCAL NAME {',' NAME} ['=' explist]
           | LOCAL *toclose NAME '=' exp */
  if (testnext(ls, '<'))
    attriblocalstat(ls);
  else
    commonlocalstat(ls);
}
static void attriblocalstat (LexState *ls) {
  Vardesc *var;
  TString *attr = str_checkname(ls);
  testnext(ls, '>');
  var = new_localvar(ls, str_checkname(ls));
  checknext(ls, '=');
  exp1(ls);
  adjustlocalvars(ls, 1);
  if (strcmp(getstr(attr), "const") == 0)
    var->ro = 1;  /* set variable as read-only */
  else if (strcmp(getstr(attr), "toclose") == 0)
    tocloselocalstat(ls, var);
  else
    luaK_semerror(ls,
      luaO_pushfstring(ls->L, "unknown attribute '%s'", getstr(attr)));
}
There is no way to extend this attributes only hard coded const and toclose

You can not write "local <const> a,b"
or if you write "local <const> a={a=1,b=2}" you can modify constant a:
"a.a=10 a.b=20"
I prefer to use runtime constants:

function const(c) return setmetatable({},{__index=c,
    __newindex=function(t,n,v) error "const is read only" end
}) end

local C=const { pi=3.14, e=2.71, B0=1, B1=2, B3=4, B4=8, print=print,
P=const{ x=1, y=2 } }
C.B1=4 -- errror const is read only

I can declare group of constants, can pass this group of constants
into functions.

> But with the last commits we got constant propagation, so I really want <const>. And if we already have annotatations probably <toclose> is worth too.
What does it mean exactly?
local<const> A=1
local B,C=A,A*A
local function f1(a) a=2 return a end
f1(A)
local function f2() A=2 end -- propagation means only this?


>
> The annotation system is a considerable addition to the language and it may seem an overkill for a single use case. But it starts to make sense when multiple issues are accounted by it.
In state it now exists they are little more than useless.
There is no annotation system. There are two hard coded cases.

> [1] E.g.:
> local function scope()
>...
Yes you can freely modify scope implementation details as you want. It
just simple function customisable for you purposes.
That's why it is much better than "local <toclose> single_var"