Skip to content

compat: shadow numeric for control variables on 5.4+ - #1165

Merged
hishamhm merged 2 commits into
teal-language:mainfrom
JJH090501:fix-fornum-control-var
Aug 26, 2026
Merged

compat: shadow numeric for control variables on 5.4+#1165
hishamhm merged 2 commits into
teal-language:mainfrom
JJH090501:fix-fornum-control-var

Conversation

@JJH090501

Copy link
Copy Markdown
Contributor

Closes #1164. Option 1, as decided in the issue: mirror the forin shadow
rather than making numeric control variables const in all targets.

Problem

lua_compat.adjust_code only had a forin case, so plain (non-macro) code that
writes to a numeric for variable type checks and then generates invalid Lua:

local t: {string} = { "a", "b", "c" }

for i = 1, #t do
   i = i + 0
   print(t[i])
end
$ lua5.5 ./tl run fornum.tl
Internal Compiler Error: Teal generator produced invalid Lua. Please report a bug at https://github.com/teal-language/tl

fornum.tl:3: attempt to assign to const variable 'i'

Change

  • teal/ast.tlfornum_modifies_control_var on Node.
  • teal/check/visitors.tl — the fornum visitor sets it from
    has_been_written_to, the same way forin does, so writes from nested
    functions are covered too.
  • teal/gen/lua_compat.tl — a fornum case. The shadow construction that was
    inlined in the forin case is factored out into shadow_control_var() and
    shared; the new case is six lines.

The shadow is a no-op in every target, since writing to a numeric for variable
has never affected the iteration:

$ lua5.1 -e 'for i=1,3 do i = i + 100; io.write(i," ") end'
101 102 103

Tests

spec/lang/code_gen/fornum_spec.lua, deliberately parallel to forin_spec.lua:
no shadow on 5.3, a shadow on 5.4 when the body assigns, none when it does not,
a loop with an explicit step, an assignment made from a nested function, and
nested loops where only the inner one is written to.

make selfbuild clean, busted --suppress-pending spec/ 1932 → 1938. The
reproduction above was verified end to end on Lua 5.5.1.

@hishamhm
hishamhm merged commit e9f09e0 into teal-language:main Aug 26, 2026
7 of 8 checks passed
@hishamhm

Copy link
Copy Markdown
Member

@JJH090501 Thank you! Rebased and merged!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

--gen-target=5.5 emits invalid Lua for numeric for loops that assign to the control variable

2 participants