From e44f3a2ffc7ced5e75cca7657aaa60ef27da89aa Mon Sep 17 00:00:00 2001 From: Roberto I Date: Sat, 8 Nov 2025 11:43:42 -0300 Subject: 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. --- lparser.c | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) (limited to 'lparser.c') diff --git a/lparser.c b/lparser.c index 40a30ff6..77141e79 100644 --- a/lparser.c +++ b/lparser.c @@ -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 */ } -- cgit v1.2.3-55-g6feb