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. --- testes/goto.lua | 21 ++++++++++++++++++++- testes/memerr.lua | 4 ++-- 2 files changed, 22 insertions(+), 3 deletions(-) (limited to 'testes') diff --git a/testes/goto.lua b/testes/goto.lua index a692a623..906208b5 100644 --- a/testes/goto.lua +++ b/testes/goto.lua @@ -293,6 +293,7 @@ end foo() -------------------------------------------------------------------------- +-- check for compilation errors local function checkerr (code, err) local st, msg = load(code) assert(not st and string.find(msg, err)) @@ -414,22 +415,26 @@ end do print "testing initialization in global declarations" global a, b, c = 10, 20, 30 assert(_ENV.a == 10 and b == 20 and c == 30) + _ENV.a = nil; _ENV.b = nil; _ENV.c = nil; global a, b, c = 10 assert(_ENV.a == 10 and b == nil and c == nil) + _ENV.a = nil; _ENV.b = nil; _ENV.c = nil; global table global a, b, c, d = table.unpack{1, 2, 3, 6, 5} assert(_ENV.a == 1 and b == 2 and c == 3 and d == 6) + a = nil; b = nil; c = nil; d = nil local a, b = 100, 200 do global a, b = a, b end assert(_ENV.a == 100 and _ENV.b == 200) + _ENV.a = nil; _ENV.b = nil - _ENV.a, _ENV.b, _ENV.c, _ENV.d = nil -- erase these globals + assert(_ENV.a == nil and _ENV.b == nil and _ENV.c == nil and _ENV.d == nil) end do @@ -454,5 +459,19 @@ do assert(env.a == 10 and env.b == 20 and env.c == 30) end + +do -- testing global redefinitions + -- cannot use 'checkerr' as errors are not compile time + global pcall + local f = assert(load("global print = 10")) + local st, msg = pcall(f) + assert(string.find(msg, "global 'print' already defined")) + + local f = assert(load("local _ENV = {AA = false}; global AA = 10")) + local st, msg = pcall(f) + assert(string.find(msg, "global 'AA' already defined")) + +end + print'OK' diff --git a/testes/memerr.lua b/testes/memerr.lua index 2cc8f481..9c940ca7 100644 --- a/testes/memerr.lua +++ b/testes/memerr.lua @@ -166,9 +166,9 @@ local function expand (n,s) e, s, expand(n-1,s), e) end -G=0; collectgarbage(); a =collectgarbage("count") +G=0; collectgarbage() load(expand(20,"G=G+1"))() -assert(G==20); collectgarbage(); -- assert(gcinfo() <= a+1) +assert(G==20); collectgarbage() G = nil testamem("running code on new thread", function () -- cgit v1.2.3-55-g6feb