diff options
| author | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 2022-12-21 12:04:59 -0300 |
|---|---|---|
| committer | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 2022-12-21 12:04:59 -0300 |
| commit | b2f7b3b79f3117885b265575f6c5dbf934757797 (patch) | |
| tree | ad7ac30fb9a05e1e6635110f03c45b9cd41190c8 /testes/closure.lua | |
| parent | 540d8052265776451bb9f0ab4dee4ec860563cbe (diff) | |
| download | lua-b2f7b3b79f3117885b265575f6c5dbf934757797.tar.gz lua-b2f7b3b79f3117885b265575f6c5dbf934757797.tar.bz2 lua-b2f7b3b79f3117885b265575f6c5dbf934757797.zip | |
Control variables in for loops are read only
Diffstat (limited to 'testes/closure.lua')
| -rw-r--r-- | testes/closure.lua | 19 |
1 files changed, 8 insertions, 11 deletions
diff --git a/testes/closure.lua b/testes/closure.lua index c2453677..27ec5596 100644 --- a/testes/closure.lua +++ b/testes/closure.lua | |||
| @@ -60,32 +60,29 @@ end | |||
| 60 | -- testing closures with 'for' control variable | 60 | -- testing closures with 'for' control variable |
| 61 | a = {} | 61 | a = {} |
| 62 | for i=1,10 do | 62 | for i=1,10 do |
| 63 | a[i] = {set = function(x) i=x end, get = function () return i end} | 63 | a[i] = function () return i end |
| 64 | if i == 3 then break end | 64 | if i == 3 then break end |
| 65 | end | 65 | end |
| 66 | assert(a[4] == undef) | 66 | assert(a[4] == undef) |
| 67 | a[1].set(10) | 67 | assert(a[2]() == 2) |
| 68 | assert(a[2].get() == 2) | 68 | assert(a[3]() == 3) |
| 69 | a[2].set('a') | ||
| 70 | assert(a[3].get() == 3) | ||
| 71 | assert(a[2].get() == 'a') | ||
| 72 | 69 | ||
| 73 | a = {} | 70 | a = {} |
| 74 | local t = {"a", "b"} | 71 | local t = {"a", "b"} |
| 75 | for i = 1, #t do | 72 | for i = 1, #t do |
| 76 | local k = t[i] | 73 | local k = t[i] |
| 77 | a[i] = {set = function(x, y) i=x; k=y end, | 74 | a[i] = {set = function(x) k=x end, |
| 78 | get = function () return i, k end} | 75 | get = function () return i, k end} |
| 79 | if i == 2 then break end | 76 | if i == 2 then break end |
| 80 | end | 77 | end |
| 81 | a[1].set(10, 20) | 78 | a[1].set(10) |
| 82 | local r,s = a[2].get() | 79 | local r,s = a[2].get() |
| 83 | assert(r == 2 and s == 'b') | 80 | assert(r == 2 and s == 'b') |
| 84 | r,s = a[1].get() | 81 | r,s = a[1].get() |
| 85 | assert(r == 10 and s == 20) | 82 | assert(r == 1 and s == 10) |
| 86 | a[2].set('a', 'b') | 83 | a[2].set('a') |
| 87 | r,s = a[2].get() | 84 | r,s = a[2].get() |
| 88 | assert(r == "a" and s == "b") | 85 | assert(r == 2 and s == "a") |
| 89 | 86 | ||
| 90 | 87 | ||
| 91 | -- testing closures with 'for' control variable x break | 88 | -- testing closures with 'for' control variable x break |
