From c0adc5f8a5a2ab00139837291c914625df942257 Mon Sep 17 00:00:00 2001 From: Roberto I Date: Fri, 28 Aug 2026 09:27:47 -0300 Subject: [PATCH 01/14] Macro 'luaC_condGC' should call pre/pos only once With test option HARDMEMTESTS defined, luaC_condGC was calling pre and pos twice. That made macro checkGC set the stack top before the GC step and then again before the full collection, but the previous step could invalidate the pointer used to set top. --- lgc.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lgc.h b/lgc.h index ee0541793b..193ac0fc50 100644 --- a/lgc.h +++ b/lgc.h @@ -231,8 +231,9 @@ #endif #define luaC_condGC(L,pre,pos) \ - { if (G(L)->GCdebt <= 0) { pre; luaC_step(L); pos;}; \ - condchangemem(L,pre,pos,0); } + { if (G(L)->GCdebt <= 0) \ + { pre; luaC_step(L); condchangemem(L,{},{},0); pos;} \ + else condchangemem(L,pre,pos,0); } /* more often than not, 'pre'/'pos' are empty */ #define luaC_checkGC(L) luaC_condGC(L,(void)0,(void)0) From 35a87f8c5bdeeea285cef38002a962d2361e4807 Mon Sep 17 00:00:00 2001 From: Roberto I Date: Sun, 13 Sep 2026 14:08:50 -0300 Subject: [PATCH 02/14] Added casts to uses of 'sig_atomic' 'sig_atomic' can be larger than 'int' on some platforms. --- ldebug.c | 2 +- lvm.c | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ldebug.c b/ldebug.c index 5293ccb9f3..61c5274989 100644 --- a/ldebug.c +++ b/ldebug.c @@ -150,7 +150,7 @@ LUA_API lua_Hook lua_gethook (lua_State *L) { LUA_API int lua_gethookmask (lua_State *L) { - return L->hookmask; + return cast_int(L->hookmask); } diff --git a/lvm.c b/lvm.c index 986c7db894..46170534c3 100644 --- a/lvm.c +++ b/lvm.c @@ -1117,7 +1117,7 @@ void luaV_finishOp (lua_State *L) { -#define updatetrap(ci) (trap = ci->u.l.trap) +#define updatetrap(ci) (trap = cast_int(ci->u.l.trap)) #define updatebase(ci) (base = ci->func.p + 1) @@ -1211,7 +1211,7 @@ void luaV_execute (lua_State *L, CallInfo *ci) { #include "ljumptab.h" #endif startfunc: - trap = L->hookmask; + trap = cast_int(L->hookmask); returning: /* trap already set */ cl = ci_func(ci); k = cl->p->k; From 4c32b2dfd204add9a3fed8d5eb100236e276e44a Mon Sep 17 00:00:00 2001 From: Roberto I Date: Tue, 15 Sep 2026 09:49:44 -0300 Subject: [PATCH 03/14] 'mktime' can return -1 --- loslib.c | 25 +++++++++++++++++-------- testes/files.lua | 7 +++++++ 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/loslib.c b/loslib.c index b7a2b0d15f..fe9295c767 100644 --- a/loslib.c +++ b/loslib.c @@ -345,11 +345,22 @@ static int os_date (lua_State *L) { } +static int os_time_aux (lua_State *L, time_t t, int err) { + if (err || t != (time_t)(l_timet)t) + return luaL_error(L, + "time result cannot be represented in this installation"); + l_pushtime(L, t); + return 1; +} + + static int os_time (lua_State *L) { - time_t t; - if (lua_isnoneornil(L, 1)) /* called without args? */ - t = time(NULL); /* get current time */ + if (lua_isnoneornil(L, 1)) { /* called without args? */ + time_t t = time(NULL); /* get current time; error if it is -1 */ + return os_time_aux(L, t, (t == (time_t)(-1))); + } else { + time_t t; struct tm ts; luaL_checktype(L, 1, LUA_TTABLE); lua_settop(L, 1); /* make sure table is at the top */ @@ -360,14 +371,12 @@ static int os_time (lua_State *L) { ts.tm_min = getfield(L, "min", 0, 0); ts.tm_sec = getfield(L, "sec", 0, 0); ts.tm_isdst = getboolfield(L, "isdst"); + ts.tm_wday = -1; /* if call succeeds, it will set this value */ t = mktime(&ts); setallfields(L, &ts); /* update fields with normalized values */ + /* error if tm_wday was not set */ + return os_time_aux(L, t, ts.tm_wday == -1); } - if (t != (time_t)(l_timet)t || t == (time_t)(-1)) - return luaL_error(L, - "time result cannot be represented in this installation"); - l_pushtime(L, t); - return 1; } diff --git a/testes/files.lua b/testes/files.lua index 7146ac7ca2..0493656588 100644 --- a/testes/files.lua +++ b/testes/files.lua @@ -854,6 +854,13 @@ local function checkDateTable (t) _G.D = nil end + +do -- testing mktime returning -1 + local t = os.date("*t", -1) + assert(os.time(t) == -1) +end + + checkDateTable(os.time()) if not _port then -- assume that time_t can represent these values From ceb32fb5bc29e3fe0009d54139081efbdf125cd4 Mon Sep 17 00:00:00 2001 From: Roberto I Date: Tue, 15 Sep 2026 10:03:36 -0300 Subject: [PATCH 04/14] Another try for silencing MSVS warning C4334 See also commit 8fac494. --- lobject.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lobject.h b/lobject.h index bf5b65b469..82bd970370 100644 --- a/lobject.h +++ b/lobject.h @@ -827,7 +827,7 @@ typedef struct Table { #define twoto(x) (1u<<(x)) -#define sizenode(t) (twoto((t)->lsizenode)) +#define sizenode(t) cast_uint(twoto((t)->lsizenode)) /* size of buffer for 'luaO_utf8esc' function */ From 973777c74efe207ddddc6677b507007dea05dfdd Mon Sep 17 00:00:00 2001 From: Roberto I Date: Wed, 16 Sep 2026 11:49:35 -0300 Subject: [PATCH 05/14] Details --- lmathlib.c | 44 ++++++++++++++++++++++---------------------- loslib.c | 20 ++++++++++---------- manual/manual.of | 4 ++-- 3 files changed, 34 insertions(+), 34 deletions(-) diff --git a/lmathlib.c b/lmathlib.c index a6b13f969c..87e7462a98 100644 --- a/lmathlib.c +++ b/lmathlib.c @@ -704,35 +704,35 @@ static int math_log10 (lua_State *L) { static const luaL_Reg mathlib[] = { - {"abs", math_abs}, - {"acos", math_acos}, - {"asin", math_asin}, - {"atan", math_atan}, - {"ceil", math_ceil}, - {"cos", math_cos}, - {"deg", math_deg}, - {"exp", math_exp}, + {"abs", math_abs}, + {"acos", math_acos}, + {"asin", math_asin}, + {"atan", math_atan}, + {"ceil", math_ceil}, + {"cos", math_cos}, + {"deg", math_deg}, + {"exp", math_exp}, {"tointeger", math_toint}, {"floor", math_floor}, - {"fmod", math_fmod}, + {"fmod", math_fmod}, {"frexp", math_frexp}, - {"ult", math_ult}, + {"ult", math_ult}, {"ldexp", math_ldexp}, - {"log", math_log}, - {"max", math_max}, - {"min", math_min}, - {"modf", math_modf}, - {"rad", math_rad}, - {"sin", math_sin}, - {"sqrt", math_sqrt}, - {"tan", math_tan}, + {"log", math_log}, + {"max", math_max}, + {"min", math_min}, + {"modf", math_modf}, + {"rad", math_rad}, + {"sin", math_sin}, + {"sqrt", math_sqrt}, + {"tan", math_tan}, {"type", math_type}, #if defined(LUA_COMPAT_MATHLIB) {"atan2", math_atan}, - {"cosh", math_cosh}, - {"sinh", math_sinh}, - {"tanh", math_tanh}, - {"pow", math_pow}, + {"cosh", math_cosh}, + {"sinh", math_sinh}, + {"tanh", math_tanh}, + {"pow", math_pow}, {"log10", math_log10}, #endif /* placeholders */ diff --git a/loslib.c b/loslib.c index fe9295c767..111ac2f811 100644 --- a/loslib.c +++ b/loslib.c @@ -416,17 +416,17 @@ static int os_exit (lua_State *L) { static const luaL_Reg syslib[] = { - {"clock", os_clock}, - {"date", os_date}, - {"difftime", os_difftime}, - {"execute", os_execute}, - {"exit", os_exit}, - {"getenv", os_getenv}, - {"remove", os_remove}, - {"rename", os_rename}, + {"clock", os_clock}, + {"date", os_date}, + {"difftime", os_difftime}, + {"execute", os_execute}, + {"exit", os_exit}, + {"getenv", os_getenv}, + {"remove", os_remove}, + {"rename", os_rename}, {"setlocale", os_setlocale}, - {"time", os_time}, - {"tmpname", os_tmpname}, + {"time", os_time}, + {"tmpname", os_tmpname}, {NULL, NULL} }; diff --git a/manual/manual.of b/manual/manual.of index e2d1a65168..e3c7cd257f 100644 --- a/manual/manual.of +++ b/manual/manual.of @@ -6071,8 +6071,8 @@ In both cases, the function pushes onto the stack the final value associated with @id{tname} in the registry. -Usage note: Beware the use of the return value of this function to -conditionally initializes the new metatable +Usage note: Beware the use of the return value of this function +to conditionally initialize the new metatable (e.g., by adding metamethods to it). If the initialization raises an error, the metatable will not be properly initialized, From 0b29f408433e92953cc72b1d3e06c7ac8139e439 Mon Sep 17 00:00:00 2001 From: Roberto I Date: Wed, 16 Sep 2026 14:18:11 -0300 Subject: [PATCH 06/14] Bug: UB when applying GC parameter When computing whether Lua should return from gen-major to gen-minor, the difference between the total memory and the previous total memory can be negative, which can result in that negative value being left-shifted (UB). --- lgc.c | 3 ++- lobject.c | 1 + testes/gengc.lua | 45 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+), 1 deletion(-) diff --git a/lgc.c b/lgc.c index a463e41e6d..cf4160c1dc 100644 --- a/lgc.c +++ b/lgc.c @@ -1472,7 +1472,8 @@ static int checkmajorminor (lua_State *L, global_State *g) { if (g->gckind == KGC_GENMAJOR) { /* generational mode? */ l_mem numbytes = gettotalbytes(g); l_mem addedbytes = numbytes - g->GCmajorminor; - l_mem limit = applygcparam(g, MAJORMINOR, addedbytes); + l_mem limit = (addedbytes < 0) ? 0 + : applygcparam(g, MAJORMINOR, addedbytes); l_mem tobecollected = numbytes - g->GCmarked; if (tobecollected > limit) { atomic2gen(L, g); /* return to generational mode */ diff --git a/lobject.c b/lobject.c index 763b484609..6997cfd021 100644 --- a/lobject.c +++ b/lobject.c @@ -89,6 +89,7 @@ lu_byte luaO_codeparam (unsigned int p) { l_mem luaO_applyparam (lu_byte p, l_mem x) { int m = p & 0xF; /* mantissa */ int e = (p >> 4); /* exponent */ + lua_assert(x >= 0); if (e > 0) { /* normalized? */ e--; /* correct exponent */ m += 0x10; /* correct mantissa; maximum value is 0x1F */ diff --git a/testes/gengc.lua b/testes/gengc.lua index 6509e39d8a..84c1a8eec0 100644 --- a/testes/gengc.lua +++ b/testes/gengc.lua @@ -162,6 +162,51 @@ end assert(collectgarbage'isrunning') +do + -- bug in 5.0: when computing whether it should return from gen-major + -- to gen-minor, the difference between the total memory and the + -- previous total memory can be negative, which results in that + -- negative value being left-shifted (UB) + + local lim = 1e6 + + -- make major collections non-incremental + local oldsm = collectgarbage("param", "stepmul", 0) + + -- make "majorminor" large enough to force a left-shift + -- when applying the parameter (internal details) + local oldmm = collectgarbage("param", "majorminor", 2000) + + collectgarbage(); collectgarbage() + assert(not T or T.gcquery() == "genminor") + + local M = collectgarbage"count" * 1024 + + -- create a large table + local t = {} + for i = 1, lim do t[i] = true end + assert(collectgarbage"count" * 1024 > M + lim * string.packsize"j") + + -- force collector to "generational major" mode, doing several + -- minor collections that recover no memory + collectgarbage"step"; collectgarbage"step"; collectgarbage"step" + assert(not T or T.gcquery() == "genmajor") + + -- shrink the table + for i = 1, lim do t[i] = nil end + t[2 * lim] = true + assert(collectgarbage"count" < M * 5/4) + + -- bug was here, an assert violation when checking whether to + -- return to 'genminor' + collectgarbage"step" + + -- restore previous parameters + collectgarbage("param", "stepmul", oldsm) + collectgarbage("param", "majorminor", oldmm) +end + + do print"testing stop-the-world collection" local step = collectgarbage("param", "stepsize", 0); collectgarbage("incremental") From 745b96db545b3260047906b4bf1901b30b229f93 Mon Sep 17 00:00:00 2001 From: Roberto I Date: Wed, 7 Oct 2026 16:02:48 -0300 Subject: [PATCH 07/14] Correction of maximum string size in 'lundump' The maximum size for internal strings in Lua is MAX_SIZE minus 'sizeof(TString)'. Moreover, 'loadVarint' must be precise about the limit of the integer being read. --- lundump.c | 23 ++++++++++------------- testes/code.lua | 1 + testes/math.lua | 6 ++++++ 3 files changed, 17 insertions(+), 13 deletions(-) diff --git a/lundump.c b/lundump.c index d5fdc64b02..7ab340cb5d 100644 --- a/lundump.c +++ b/lundump.c @@ -96,11 +96,12 @@ static lu_byte loadByte (LoadState *S) { static lua_Unsigned loadVarint (LoadState *S, lua_Unsigned limit) { lua_Unsigned x = 0; + lua_Unsigned limit_high = limit >> 7; + int limit_low = limit & 0x7f; int b; - limit >>= 7; do { b = loadByte(S); - if (x > limit) + if (x >= limit_high && (x > limit_high || (b & 0x7f) > limit_low)) error(S, "integer overflow"); x = (x << 7) | (b & 0x7f); } while ((b & 0x80) != 0); @@ -108,11 +109,6 @@ static lua_Unsigned loadVarint (LoadState *S, lua_Unsigned limit) { } -static size_t loadSize (LoadState *S) { - return cast_sizet(loadVarint(S, MAX_SIZE)); -} - - static int loadInt (LoadState *S) { return cast_int(loadVarint(S, cast_sizet(INT_MAX))); } @@ -137,16 +133,17 @@ static lua_Integer loadInteger (LoadState *S) { /* -** Load a nullable string into slot 'sl' from prototype 'p'. The -** assignment to the slot and the barrier must be performed before any -** possible GC activity, to anchor the string. (Both 'loadVector' and -** 'luaH_setint' can call the GC.) +** Load a nullable string into slot 'sl' from prototype 'p'. 'size' is +** either the string length + 1 or zero for a previously saved string. +** The assignment to the slot and the barrier must be performed before +** any possible GC activity, to anchor the string. (Both 'loadVector' +** and 'luaH_setint' can call the GC.) */ static void loadString (LoadState *S, Proto *p, TString **sl) { lua_State *L = S->L; TString *ts; TValue sv; - size_t size = loadSize(S); + size_t size = cast_sizet(loadVarint(S, MAX_SIZE - sizeof(TString) + 1)); if (size == 0) { /* previously saved string? */ lua_Unsigned idx = loadVarint(S, LUA_MAXUNSIGNED); /* get its index */ TValue stv; @@ -160,7 +157,7 @@ static void loadString (LoadState *S, Proto *p, TString **sl) { luaC_objbarrier(L, p, ts); return; /* do not save it again */ } - else if ((size -= 1) <= LUAI_MAXSHORTLEN) { /* short string? */ + else if (--size <= LUAI_MAXSHORTLEN) { /* short string? */ char buff[LUAI_MAXSHORTLEN + 1]; /* extra space for '\0' */ loadVector(S, buff, size + 1); /* load string into buffer */ *sl = ts = luaS_newlstr(L, buff, size); /* create string */ diff --git a/testes/code.lua b/testes/code.lua index 380ff70c1b..ba331d272b 100644 --- a/testes/code.lua +++ b/testes/code.lua @@ -303,6 +303,7 @@ checkI(function () return 0xF0.0 | 0xCC.0 ~ 0xAA & 0xFD end, 0xF4) checkI(function () return ~(~kFF0 | kFF0) end, 0) checkI(function () return ~~-1024.0 end, -1024) checkI(function () return ((100 << k6) << -4) >> 2 end, 100) +checkK(function () return ~(-1 >> 1) end, math.mininteger) -- borders around MAXARG_sBx ((((1 << 17) - 1) >> 1) == 65535) local a = 17; local sbx = ((1 << a) - 1) >> 1 -- avoid folding diff --git a/testes/math.lua b/testes/math.lua index 54d19c4075..ab74676a89 100644 --- a/testes/math.lua +++ b/testes/math.lua @@ -385,6 +385,12 @@ do assert(minint == load("return " .. minint)()) assert(eqT(maxint, load("return " .. maxint)())) + -- limit for integer encoding in binary chunks + -- (~(-1 >> 1) is optimized by the compiler as minint, which is + -- then encoded in a binary chunk as max unsigned) + local f = string.dump(function () return ~(-1 >> 1) end) + assert(load(f)() == minint) + assert(eqT(10000000000000000000000.0, 10000000000000000000000)) assert(eqT(-10000000000000000000000.0, -10000000000000000000000)) end From 80f3ecc44f1b137cde86c7a7821209a2d88cbdf1 Mon Sep 17 00:00:00 2001 From: Roberto I Date: Mon, 12 Oct 2026 16:12:40 -0300 Subject: [PATCH 08/14] Avoid underflows in 'luaF_getlocalname' A call like 'debug.getlocal(test, -2147483648)' could decrement -2147483648, causing an underflow. (As this happens in a debug function, the fix was not strictly necessary, but it has no cost in the generated code.) --- ldebug.c | 6 +++--- lfunc.c | 2 +- lfunc.h | 4 ++-- ltests.c | 2 +- testes/db.lua | 1 + 5 files changed, 8 insertions(+), 7 deletions(-) diff --git a/ldebug.c b/ldebug.c index 61c5274989..58d8731e2f 100644 --- a/ldebug.c +++ b/ldebug.c @@ -202,7 +202,7 @@ const char *luaG_findlocal (lua_State *L, CallInfo *ci, int n, StkId *pos) { if (n < 0) /* access to vararg values? */ return findvararg(ci, n, pos); else - name = luaF_getlocalname(ci_func(ci)->p, n, currentpc(ci)); + name = luaF_getlocalname(ci_func(ci)->p, cast_uint(n), currentpc(ci)); } if (name == NULL) { /* no 'standard' name? */ StkId limit = (ci == L->ci) ? L->top.p : ci->next->func.p; @@ -226,7 +226,7 @@ LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) { if (!isLfunction(s2v(L->top.p - 1))) /* not a Lua function? */ name = NULL; else /* consider live variables at function start (parameters) */ - name = luaF_getlocalname(clLvalue(s2v(L->top.p - 1))->p, n, 0); + name = luaF_getlocalname(clLvalue(s2v(L->top.p - 1))->p, cast_uint(n), 0); } else { /* active function; get information through 'ar' */ StkId pos = NULL; /* to avoid warnings */ @@ -505,7 +505,7 @@ static const char *kname (const Proto *p, int index, const char **name) { static const char *basicgetobjname (const Proto *p, int *ppc, int reg, const char **name) { int pc = *ppc; - *name = luaF_getlocalname(p, reg + 1, pc); + *name = luaF_getlocalname(p, cast_uint(reg + 1), pc); if (*name) /* is a local? */ return strlocal; /* else try symbolic execution */ diff --git a/lfunc.c b/lfunc.c index b6fd9ceb55..84a5b18610 100644 --- a/lfunc.c +++ b/lfunc.c @@ -300,7 +300,7 @@ void luaF_freeproto (lua_State *L, Proto *f) { ** Look for n-th local variable at line 'line' in function 'func'. ** Returns NULL if not found. */ -const char *luaF_getlocalname (const Proto *f, int local_number, int pc) { +const char *luaF_getlocalname (const Proto *f, unsigned local_number, int pc) { int i; for (i = 0; isizelocvars && f->locvars[i].startpc <= pc; i++) { if (pc < f->locvars[i].endpc) { /* is variable active? */ diff --git a/lfunc.h b/lfunc.h index d6aad3a6df..e53a4974dc 100644 --- a/lfunc.h +++ b/lfunc.h @@ -58,8 +58,8 @@ LUAI_FUNC StkId luaF_close (lua_State *L, StkId level, TStatus status, int yy); LUAI_FUNC void luaF_unlinkupval (UpVal *uv); LUAI_FUNC lu_mem luaF_protosize (Proto *p); LUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f); -LUAI_FUNC const char *luaF_getlocalname (const Proto *func, int local_number, - int pc); +LUAI_FUNC const char *luaF_getlocalname (const Proto *func, + unsigned local_number, int pc); #endif diff --git a/ltests.c b/ltests.c index 2bf5545a49..6bfd55f98b 100644 --- a/ltests.c +++ b/ltests.c @@ -853,7 +853,7 @@ static int listlocals (lua_State *L) { luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1), 1, "Lua function expected"); p = getproto(obj_at(L, 1)); - while ((name = luaF_getlocalname(p, ++i, pc)) != NULL) + while ((name = luaF_getlocalname(p, cast_uint(++i), pc)) != NULL) lua_pushstring(L, name); return i-1; } diff --git a/testes/db.lua b/testes/db.lua index e15a5be6bd..e754c06d37 100644 --- a/testes/db.lua +++ b/testes/db.lua @@ -258,6 +258,7 @@ print'+' -- invalid levels in [gs]etlocal assert(not pcall(debug.getlocal, 20, 1)) assert(not pcall(debug.setlocal, -1, 1, 10)) +assert(not debug.getlocal(test, -2147483648)) -- parameter names From e8533201cd2448d668c9b64758fc44205544b27f Mon Sep 17 00:00:00 2001 From: Roberto I Date: Mon, 12 Oct 2026 16:14:08 -0300 Subject: [PATCH 09/14] Bug: Wrong semantics in numeric for loop with NaN A numeric for loop with a NaN (Not a Number) limit should never run, as the initial value is neither smaller or equal nor greater or equal to that limit. --- lvm.c | 7 ++++--- testes/nextvar.lua | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/lvm.c b/lvm.c index 46170534c3..cd3a36653b 100644 --- a/lvm.c +++ b/lvm.c @@ -190,10 +190,11 @@ static int forlimit (lua_State *L, lua_Integer init, const TValue *lim, if (step < 0) return 1; /* initial value must be less than it */ *p = LUA_MAXINTEGER; /* truncate */ } - else { /* it is less than min integer */ + else if (luai_numgt(0, flim)) { /* if it is negative, it is too small */ if (step > 0) return 1; /* initial value must be greater than it */ *p = LUA_MININTEGER; /* truncate */ } + else return 1; /* limit is NaN (neither 0 nor positive nor negative) */ } return (step > 0 ? init > *p : init < *p); /* not to run? */ } @@ -251,8 +252,8 @@ static int forprep (lua_State *L, StkId ra) { luaG_forerror(L, pinit, "initial value"); if (step == 0) luaG_runerror(L, "'for' step is zero"); - if (luai_numlt(0, step) ? luai_numlt(limit, init) - : luai_numlt(init, limit)) + if (!(luai_numge(0, step) ? luai_numge(init, limit) + : luai_numge(limit, init))) return 1; /* skip the loop */ else { /* make sure all values are floats */ diff --git a/testes/nextvar.lua b/testes/nextvar.lua index 098e7891c9..beb2e632c9 100644 --- a/testes/nextvar.lua +++ b/testes/nextvar.lua @@ -734,6 +734,22 @@ do a = 0; for i=1.0, 0.99999, -1 do a=a+1 end; assert(a==1) end +do print("testing NaN in numeric for") + local NaN = 0/0 + + for i = 1, NaN, 1 do error("should not run the loop") end + for i = 1, NaN, -1 do error("should not run the loop") end + for i = 1.0, NaN do error("should not run the loop") end + for i = 1.0, NaN, -1 do error("should not run the loop") end + for i = NaN, 1 do error("should not run the loop") end + for i = NaN, 1, -1 do error("should not run the loop") end + + -- NaN is not negative, so the loop must be ascending + -- (that's somewhat arbitrary) + for i = 2, 1, NaN do error("should not run the loop") end + local s = 0; for i = 1, 5, NaN do s = s + 1 end; assert(s == 1) +end + do -- attempt to change the control variable local st, msg = load "for i = 1, 10 do i = 10 end" assert(not st and string.find(msg, "assign to const variable 'i'")) From 6db80b55c1df245a468660b03105a3a083269ca5 Mon Sep 17 00:00:00 2001 From: Roberto I Date: Mon, 12 Oct 2026 16:25:19 -0300 Subject: [PATCH 10/14] Small corrections/improvements in the manual --- manual/manual.of | 77 ++++++++++++++++++++++++------------------------ 1 file changed, 39 insertions(+), 38 deletions(-) diff --git a/manual/manual.of b/manual/manual.of index e3c7cd257f..7cdc1ce31d 100644 --- a/manual/manual.of +++ b/manual/manual.of @@ -37,11 +37,11 @@ The host program can invoke functions to execute a piece of Lua code, can write and read Lua variables, and can register @N{C functions} to be called by Lua code. Through the use of @N{C functions}, Lua can be augmented to cope with -a wide range of different domains, +a wide range of domains, thus creating customized programming languages sharing a syntactical framework. -Lua is free software, -and is provided as usual with no guarantees, +Lua is free software +and is provided with no guarantees, as stated in its license. The implementation described in this manual is available at Lua's official web site, @id{www.lua.org}. @@ -92,7 +92,7 @@ Despite its name, @false is frequently used as an alternative to @nil, with the key difference that @false behaves like a regular value in a table, -while a @nil in a table represents an absent key. +while @nil in a table represents an absent key. The type @emph{number} represents both integer numbers and real (floating-point) numbers, @@ -373,7 +373,7 @@ Lua itself only generates errors whose error object is a string, but programs can generate errors with any value as the error object, except @nil. -(Lua will change a @nil as error object to a string message.) +(Lua will change a @nil value as error object to a string message.) It is up to the Lua program or its host to handle such error objects. For historical reasons, an error object is often called an @def{error message}, @@ -441,7 +441,7 @@ except by using the @link{debuglib|debug library}. Tables and full userdata have individual metatables, although multiple tables and userdata can share their metatables. Values of all other types share one single metatable per type; -that is, there is one single metatable for all numbers, +that is, there is a single metatable for all numbers, one for all strings, etc. By default, a value has no metatable, but the string library sets a metatable for the string type @see{strlib}. @@ -665,11 +665,11 @@ Some functions in the standard library (e.g., @Lid{tostring}) use other fields in metatables for their own purposes. -It is a good practice to add all needed metamethods to a table +It is good practice to add all needed metamethods to a table before setting it as a metatable of some object. In particular, the @idx{__gc} metamethod works only when this order is followed @see{finalizers}. -It is also a good practice to set the metatable of an object +It is also good practice to set the metatable of an object right after its creation. } @@ -712,7 +712,7 @@ The garbage collector (GC) in Lua can work in two modes: incremental and generational. The default GC mode with the default parameters -are adequate for most uses. +is adequate for most uses. However, programs that waste a large proportion of their time allocating and freeing memory can benefit from other settings. Keep in mind that the GC behavior is non-portable @@ -773,7 +773,7 @@ effectively producing a non-incremental, stop-the-world collector. In generational mode, the collector does frequent @emph{minor} collections, -which traverses only objects recently created. +which traverse only objects recently created. If after a minor collection the number of bytes is above a limit, the collector shifts to a @emph{major} collection, which traverses all objects. @@ -1355,8 +1355,8 @@ in the first way, interpreting the open parenthesis as the start of the arguments to a call. To avoid this ambiguity, -it is a good practice to always precede with a semicolon -statements that start with a parenthesis: +it is good practice to precede +these statements with a semicolon: @verbatim{ ;(print or io.write)('done') } @@ -1937,7 +1937,7 @@ the library calls the metamethod of the other operand (if present) or it raises an error. Note that bitwise operators do not do this coercion. -It is always a good practice not to rely on the +It is always good practice not to rely on the implicit coercions from strings to numbers, as they are not always applied; in particular, @T{"1"==1} is false and @T{"1"<1} raises an error @@ -2190,9 +2190,8 @@ The order of the assignments in a constructor is undefined. (This order would be relevant only when there are repeated keys.) If the last field in the list has the form @id{exp} -and the expression is a multires expression, -then all values returned by this expression enter the list consecutively -@see{multires}. +and the expression is a \emph{multires} expression @see{multires}, +then all values returned by this expression enter the list consecutively. The field list can have an optional trailing separator, as a convenience for machine-generated code. @@ -2435,7 +2434,8 @@ Note that an anonymous vararg table always satisfy these conditions. @sect3{multires| @title{Lists of Expressions, Multiple Results, and Adjustment} Both function calls and vararg expressions can result in multiple values. -These expressions are called @def{multires expressions}. +These expressions are called @def{multires expressions} +(\emph{multiple-return} expressions). When a multires expression is used as the last element of a list of expressions, @@ -2504,7 +2504,7 @@ in its place. Here are some examples of uses of multires expressions. In all cases, when the construction needs @Q{the n-th result} and there is no such result, -it uses a @nil. +it uses @nil. @verbatim{ print(x, f()) -- prints x and all results from f(). print(x, (f())) -- prints x and the first result from f(). @@ -3030,9 +3030,9 @@ Each function has an indicator like this: @apii{o,p,x} The first field, @T{o}, -is how many elements the function pops from the stack. +specifies how many elements the function pops from the stack. The second field, @T{p}, -is how many elements the function pushes onto the stack. +specifies how many elements the function pushes onto the stack. (Any function always pushes its results after popping its arguments.) A field in the form @T{x|y} means the function can push (or pop) @T{x} or @T{y} elements, @@ -3201,7 +3201,7 @@ Any error while calling and running the function is propagated upwards (with a @id{longjmp}). The following example shows how the host program can do the -equivalent to this Lua code: +equivalent of this Lua code: @verbatim{ a = f("how", t.x, 14) } @@ -4505,7 +4505,7 @@ with user data @id{ud}. @APIEntry{void lua_setfield (lua_State *L, int index, const char *k);| @apii{1,0,e} -Does the equivalent to @T{t[k] = v}, +Does the equivalent of @T{t[k] = v}, where @id{t} is the value at the given index and @id{v} is the value on the top of the stack. @@ -6019,7 +6019,7 @@ it does not run it. @APIEntry{unsigned int luaL_makeseed (lua_State *L);| @apii{0,0,-} -Returns a value with a weak attempt for randomness. +Returns a value with weak randomness. The parameter @id{L} can be @id{NULL} if there is no Lua state available. @@ -6464,7 +6464,7 @@ deserve an implementation in C (e.g., @Lid{table.sort}). All libraries are implemented through the official @N{C API} and are provided as separate @N{C modules}. Unless otherwise noted, -these library functions do not adjust its number of arguments +a library function does not adjust its number of arguments to its expected parameters. For instance, a function documented as @T{foo(arg)} should not be called without an argument. @@ -6781,7 +6781,9 @@ The string @id{mode} controls whether the chunk can be text or binary It may be the string @St{b} (only @x{binary chunk}s), @St{t} (only text chunks), or @St{bt} (both binary and text). -The default is @St{bt}. +The default is @St{bt}, +but it is good practice to use an explicit mode +when accepting binary chunks. Lua does not check the consistency of binary chunks. Maliciously crafted binary chunks can crash @@ -6802,7 +6804,7 @@ if no file name is given. @LibEntry{next (table [, index])| Allows a program to traverse all fields of a table. -Its first argument is a table and its second argument +The first argument is a table and the second argument is an index in this table. A call to @id{next} returns the next index of the table and its associated value. @@ -7283,7 +7285,7 @@ This is a low-level function. It completely bypasses the package and module system. Unlike @Lid{require}, it does not perform any path searching and -does not automatically adds extensions. +does not automatically add extensions. @id{libname} must be the complete file name of the @N{C library}, including if necessary a path and an extension. @id{funcname} must be the exact name exported by the @N{C library} @@ -8537,8 +8539,7 @@ equal seeds produce equal sequences of numbers. The default for @id{y} is zero. When called with no arguments, -Lua generates a seed with -a weak attempt for randomness. +Lua generates a seed with weak randomness. This function returns the two seed components that were effectively used, @@ -8628,7 +8629,7 @@ and some non-false value on success. On non-POSIX systems, the computation of the error message and error code in case of errors -may be not @x{thread safe}, +may be not @x{thread-safe}, because they rely on the global C variable @id{errno}. @LibEntry{io.close ([file])| @@ -8708,7 +8709,7 @@ which is needed in some systems to open the file in binary mode. @LibEntry{io.output ([file])| -Similar to @Lid{io.input}, but operates over the default output file. +Similar to @Lid{io.input}, but operates on the default output file. } @@ -8717,7 +8718,7 @@ Similar to @Lid{io.input}, but operates over the default output file. This function is system dependent and is not available on all platforms. -Starts the program @id{prog} in a separated process and returns +Starts the program @id{prog} in a separate process and returns a file handle that you can use to read data from this program (if @id{mode} is @T{"r"}, the default) or to write data to this program @@ -8892,8 +8893,8 @@ For the last two cases, @id{size} is a hint for the size of the buffer, in bytes. The default is an appropriate size. -The specific behavior of each mode is non portable; -check the underlying @ANSI{setvbuf} in your platform for +The specific behavior of each mode is non-portable; +check the underlying @ANSI{setvbuf} on your platform for more details. } @@ -8958,7 +8959,7 @@ which gives a human-readable date and time representation using the current locale. On non-POSIX systems, -this function may be not @x{thread safe} +this function may be not @x{thread-safe} because of its reliance on @CId{gmtime} and @CId{localtime}. } @@ -9064,7 +9065,7 @@ When called with @nil as the first argument, this function only returns the name of the current locale for the given category. -This function may be not @x{thread safe} +This function may be not @x{thread-safe} because of its reliance on @CId{setlocale}. } @@ -9628,7 +9629,7 @@ makes @id{global} a regular word. } @item{ -The control variable in @Rw{for} loops is read only. +The control variable in @Rw{for} loops is read-only. If you need to change it, declare a local variable with the same name in the loop body. } @@ -9638,7 +9639,7 @@ A chain of @id{__call} metamethods can have at most 15 objects. } @item{ -In an error, a @nil as the error object is replaced by a +In an error, @nil as the error object is replaced by a string message. } From b35736b9d71182bae67492af2a387b3f6e89fd05 Mon Sep 17 00:00:00 2001 From: Roberto I Date: Mon, 12 Oct 2026 16:27:02 -0300 Subject: [PATCH 11/14] Bug: wrong result for (-0.0 - 0) (exp - i) was being optimized to (exp + (-i)), to use OP_ADDI, but (-0.0 - 0) is -0.0, while (-0.0 + 0) is +0.0, so the case (exp - 0) was excluded from the optimization. --- lcode.c | 6 +++++- testes/math.lua | 5 +++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/lcode.c b/lcode.c index 8b61d5de92..791ec02ee4 100644 --- a/lcode.c +++ b/lcode.c @@ -1542,15 +1542,19 @@ static void codebinK (FuncState *fs, BinOpr opr, /* Try to code a binary operator negating its second operand. ** For the metamethod, 2nd operand must keep its original value. +** As a special case, avoid the optimization for (exp - 0), because +** (-0.0 - 0) is -0.0, while (-0.0 + 0) is +0.0. */ static int finishbinexpneg (FuncState *fs, expdesc *e1, expdesc *e2, - OpCode op, int line, TMS event) { + OpCode op, int line, TMS event) { if (!isKint(e2)) return 0; /* not an integer constant */ else { lua_Integer i2 = e2->u.ival; if (!(fitsC(i2) && fitsC(-i2))) return 0; /* not in the proper range */ + if (event == TM_SUB && i2 == 0) + return 0; /* do not optimize (exp - 0) */ else { /* operating a small integer constant */ int v2 = cast_int(i2); finishbinexpval(fs, e1, e2, op, int2sC(-v2), 0, line, OP_MMBINI, event); diff --git a/testes/math.lua b/testes/math.lua index ab74676a89..d09b4202c6 100644 --- a/testes/math.lua +++ b/testes/math.lua @@ -838,6 +838,11 @@ do local a1, a2, a3, a4, a5 = 0, 0, "\0\0\0\0\0\0\0\0", 0, "\0\0\0\0\0\0\0\0" assert(a1 == a2 and a2 == a4 and a1 ~= a3) assert(a3 == a5) + + -- Bug since 5.4: Results differ for constant 0 versus variable 0; + -- (mz - 0) should be -0.0, but it resulted in +0.0 + local zi = 0 + assert(1/(mz - 0) == 1/(mz - zi)) end From 15b2a78106f85a3f8ef2efe5683148d9dad84b33 Mon Sep 17 00:00:00 2001 From: Roberto I Date: Thu, 15 Oct 2026 13:53:40 -0300 Subject: [PATCH 12/14] Bug: Calling coroutine.close while closing after error A call to 'coroutine.close()' while closing the coroutine returns like 'resume', with no errors, even if the coroutine previously had stopped due to an error. --- lcorolib.c | 3 ++- lstate.c | 22 ++++++++++++++++++++-- manual/manual.of | 3 ++- testes/coroutine.lua | 20 ++++++++++++++++++-- 4 files changed, 42 insertions(+), 6 deletions(-) diff --git a/lcorolib.c b/lcorolib.c index eb30bf4da5..976ac6386c 100644 --- a/lcorolib.c +++ b/lcorolib.c @@ -78,7 +78,8 @@ static int luaB_auxwrap (lua_State *L) { int stat = lua_status(co); if (stat != LUA_OK && stat != LUA_YIELD) { /* error in the coroutine? */ stat = lua_closethread(co, L); /* close its tbc variables */ - lua_assert(stat != LUA_OK); + if (stat == LUA_OK) + return 0; /* nothing to return */ lua_xmove(co, L, 1); /* move error message to the caller */ } if (stat != LUA_ERRMEM && /* not a memory error and ... */ diff --git a/lstate.c b/lstate.c index ada0b8566a..08179357e6 100644 --- a/lstate.c +++ b/lstate.c @@ -319,18 +319,36 @@ TStatus luaE_resetthread (lua_State *L, TStatus status) { status = luaD_closeprotected(L, 1, status); if (status != LUA_OK) /* errors? */ luaD_seterrorobj(L, status, L->stack.p + 1); - else + else /* keep in the stack only the fake function-entry for basic ci */ L->top.p = L->stack.p + 1; luaD_reallocstack(L, cast_int(L->ci->top.p - L->stack.p), 0); return status; } +/* +** Auxiliary function to call luaE_resetthread in protected mode. +** That function closes all tbc variables in protected mode, so the +** only possible "error" is when a tbc variable closes the thread being +** closed and therefore calls 'luaD_throwbaselevel'; in that case, +** control goes directly back to the first call to lua_closethread (not +** to the second), to properly return it. +*/ +static void resetthread_aux (lua_State *L, void *ud) { + TStatus status = *cast(TStatus*, ud); + status = luaE_resetthread(L, status); + if (status != LUA_OK) + luaD_throw(L, status); +} + + LUA_API int lua_closethread (lua_State *L, lua_State *from) { TStatus status; lua_lock(L); L->nCcalls = (from) ? getCcalls(from) : 0; - status = luaE_resetthread(L, L->status); + status = luaD_rawrunprotected(L, resetthread_aux, &L->status); + /* stack has error message iff there was an error */ + lua_assert(L->top.p == L->stack.p + (status == LUA_OK ? 1 : 2)); if (L == from) /* closing itself? */ luaD_throwbaselevel(L, status); lua_unlock(L); diff --git a/manual/manual.of b/manual/manual.of index 7cdc1ce31d..0288249271 100644 --- a/manual/manual.of +++ b/manual/manual.of @@ -7048,7 +7048,8 @@ The given coroutine must be dead, suspended, or be the running coroutine. For the running coroutine, this function does not return. -Instead, the resume that (re)started the coroutine returns. +Instead, the resume that (re)started the coroutine returns +with no error and no results. For other coroutines, in case of error diff --git a/testes/coroutine.lua b/testes/coroutine.lua index ba394e0c46..953c157baf 100644 --- a/testes/coroutine.lua +++ b/testes/coroutine.lua @@ -156,8 +156,6 @@ do st, msg = coroutine.close(co) assert(st and msg == nil) - local main = coroutine.running() - -- cannot close 'main' local st, msg = pcall(coroutine.close, main); assert(not st and string.find(msg, "main")) @@ -184,6 +182,24 @@ do assert(st and msg == nil) end + + do + -- again close a coroutine while closing it, but with the + -- coroutine in error mode. + + -- after the error, the function created by 'wrap' will close the + -- coroutine. The close inside 'a' overrides the original close + -- and finishes the coroutine with no errors. + local co = coroutine.wrap(function() + local a = func2close(function() + coroutine.close() + end) + error("y") + end) + co() -- no errors + end + + -- to-be-closed variables in coroutines local X From 8cb93bada561977eb370819e39d7d644e5fd0a3f Mon Sep 17 00:00:00 2001 From: Roberto I Date: Fri, 16 Oct 2026 11:16:12 -0300 Subject: [PATCH 13/14] Cast in 'rl_readline_name' In Mac OS, 'rl_readline_name' is declared as 'char*', instead of 'const char*', so we cannot assign to it a string literal such as "lua". --- lua.c | 3 ++- testes/main.lua | 8 +++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/lua.c b/lua.c index 858a04c075..f07bb95e94 100644 --- a/lua.c +++ b/lua.c @@ -465,7 +465,8 @@ static int handle_luainit (lua_State *L) { #include #include -#define lua_initreadline(L) ((void)L, rl_readline_name="lua") +#define lua_initreadline(L) \ + ((void)L, *cast(const char **, &rl_readline_name)="lua") #define lua_readline(buff,prompt) ((void)buff, readline(prompt)) #define lua_saveline(line) add_history(line) #define lua_freeline(line) free(line) diff --git a/testes/main.lua b/testes/main.lua index 98d3695189..6425faf0ef 100644 --- a/testes/main.lua +++ b/testes/main.lua @@ -199,14 +199,16 @@ assert(not string.find(defaultpath, "xxx") and -- (LUA_READLINELIB was introduced in 5.5.1) if release >= "5.5.1" then + -- OBS: this test is not valid when Lua is compiled with LUA_USE_READLINE print"testing readline library name" -- should generate a warning when trying to load inexistent library "xuxu" local env = [[LUA_READLINELIB=xuxu LUA_INIT="warn('@allow')"]] local code = 'echo " " | env %s lua %s -W -i >%s 2>&1' RUN(code, env, "", out) -- run code with no extra options - assert(string.find(getoutput(), - "warning: unable to load readline library 'xuxu'")) - + if(not string.find(getoutput(), + "warning: unable to load readline library 'xuxu'")) then + error("Is Lua compiled with option LUA_USE_READLINE?") + end RUN(code, env, "-E", out) -- run again with option -E -- no warning when LUA_READLINELIB is to be ignored assert(not string.find(getoutput(), "warning")) From c42d820bc0c3bc4f2ad536e19d2f05405af10387 Mon Sep 17 00:00:00 2001 From: Roberto I Date: Fri, 6 Nov 2026 14:23:05 -0300 Subject: [PATCH 14/14] Details --- lcode.c | 1 - loadlib.c | 1 + luaconf.h | 4 ++-- testes/nextvar.lua | 11 +++++++---- 4 files changed, 10 insertions(+), 7 deletions(-) diff --git a/lcode.c b/lcode.c index 791ec02ee4..ad3f2783ce 100644 --- a/lcode.c +++ b/lcode.c @@ -1930,7 +1930,6 @@ static int finaltarget (Instruction *code, int i) { ** Do a final pass over the code of a function, doing small peephole ** optimizations and adjustments. */ -#include "lopnames.h" void luaK_finish (FuncState *fs) { int i; Proto *p = fs->f; diff --git a/loadlib.c b/loadlib.c index ef09c9a546..703bc34bbe 100644 --- a/loadlib.c +++ b/loadlib.c @@ -690,6 +690,7 @@ static const luaL_Reg pk_funcs[] = { {"path", NULL}, {"searchers", NULL}, {"loaded", NULL}, + {"config", NULL}, {NULL, NULL} }; diff --git a/luaconf.h b/luaconf.h index bdac085c2b..9a2ef3c826 100644 --- a/luaconf.h +++ b/luaconf.h @@ -383,7 +383,7 @@ /* @@ LUAI_UACNUMBER is the result of a 'default argument promotion' -@@ over a floating number. +** over a floating number. @@ l_floatatt(x) corrects float attribute 'x' to the proper float type ** by prefixing it with one of FLT/DBL/LDBL. @@ LUA_NUMBER_FRMLEN is the length modifier for writing floats. @@ -467,7 +467,7 @@ /* @@ LUA_UNSIGNED is the unsigned version of LUA_INTEGER. @@ LUAI_UACINT is the result of a 'default argument promotion' -@@ over a LUA_INTEGER. +** over a LUA_INTEGER. @@ LUA_INTEGER_FRMLEN is the length modifier for reading/writing integers. @@ LUA_INTEGER_FMT is the format for writing integers. @@ LUA_MAXINTEGER is the maximum value for a LUA_INTEGER. diff --git a/testes/nextvar.lua b/testes/nextvar.lua index beb2e632c9..9d523b7b1c 100644 --- a/testes/nextvar.lua +++ b/testes/nextvar.lua @@ -158,12 +158,15 @@ end -- testing C library sizes do - local s = 0 - for _ in pairs(math) do s = s + 1 end - check(math, 0, mp2(s)) + local debug = require "debug" + local libs = {coroutine, debug, io, math, os, package, string, table, utf8} + for _, t in ipairs(libs) do + local n = 0 + for _ in pairs(t) do n = n + 1 end -- count number of entries + check(t, 0, mp2(n)) + end end - -- testing constructor sizes local sizes = {0, 1, 2, 3, 4, 5, 7, 8, 9, 15, 16, 17, 30, 31, 32, 33, 34, 254, 255, 256, 257, 500, 1001}