Global initialization checks name conflict

Initialization "global a = 10" raises an error if global 'a' is already
defined, that is, it has a non-nil value.
This commit is contained in:
Roberto I
2025-11-08 11:43:42 -03:00
parent f791bb6906
commit e44f3a2ffc
13 changed files with 87 additions and 9 deletions

View File

@@ -1875,6 +1875,16 @@ static lu_byte getglobalattribute (LexState *ls, lu_byte df) {
}
static void checkglobal (LexState *ls, TString *varname, int line) {
FuncState *fs = ls->fs;
expdesc var;
int k;
buildglobal(ls, varname, &var); /* create global variable in 'var' */
k = var.u.ind.keystr; /* index of global name in 'k' */
luaK_codecheckglobal(fs, &var, k, line);
}
/*
** Recursively traverse list of globals to be initalized. When
** going, generate table description for the global. In the end,
@@ -1883,7 +1893,8 @@ static lu_byte getglobalattribute (LexState *ls, lu_byte df) {
** the stack to the corresponding table description. 'n' is the variable
** being handled, range [0, nvars - 1].
*/
static void initglobal (LexState *ls, int nvars, int firstidx, int n) {
static void initglobal (LexState *ls, int nvars, int firstidx, int n,
int line) {
if (n == nvars) { /* traversed all variables? */
expdesc e;
int nexps = explist(ls, &e); /* read list of expressions */
@@ -1895,8 +1906,9 @@ static void initglobal (LexState *ls, int nvars, int firstidx, int n) {
TString *varname = getlocalvardesc(fs, firstidx + n)->vd.name;
buildglobal(ls, varname, &var); /* create global variable in 'var' */
enterlevel(ls); /* control recursion depth */
initglobal(ls, nvars, firstidx, n + 1);
initglobal(ls, nvars, firstidx, n + 1, line);
leavelevel(ls);
checkglobal(ls, varname, line);
storevartop(fs, &var);
}
}
@@ -1913,7 +1925,7 @@ static void globalnames (LexState *ls, lu_byte defkind) {
nvars++;
} while (testnext(ls, ','));
if (testnext(ls, '=')) /* initialization? */
initglobal(ls, nvars, lastidx - nvars + 1, 0);
initglobal(ls, nvars, lastidx - nvars + 1, 0, ls->linenumber);
fs->nactvar = cast_short(fs->nactvar + nvars); /* activate declaration */
}
@@ -1943,6 +1955,7 @@ static void globalfunc (LexState *ls, int line) {
fs->nactvar++; /* enter its scope */
buildglobal(ls, fname, &var);
body(ls, &b, 0, ls->linenumber); /* compile and return closure in 'b' */
checkglobal(ls, fname, line);
luaK_storevar(fs, &var, &b);
luaK_fixline(fs, line); /* definition "happens" in the first line */
}