Update syntax.md

This commit is contained in:
Arseny Kapoulkine 2022-05-05 11:00:00 -07:00 committed by GitHub
parent 73ea6e9c89
commit e562fff55b
Signed by: DevComp
GPG key ID: 4AEE18F83AFDEB23

View file

@ -207,6 +207,15 @@ for k, v in {1, 4, 9} do
end
```
This works for tables but can also be extended for tables or userdata by implementing `__iter` metamethod that is called before the iteration begins, and should return an iterator function like `next` (or a custom one).
This works for tables but can also be extended for tables or userdata by implementing `__iter` metamethod that is called before the iteration begins, and should return an iterator function like `next` (or a custom one):
For tables, the iteration order is specified to be consecutive for elements `1..#t` and unordered after that, visiting every element; similarly to iteration using `pairs`, modifying the table entries for keys other than the current one results in unspecified behavior.
```lua
local obj = { items = {1, 4, 9} }
setmetatable(obj, { __iter = function(o) return next, o.items end })
for k, v in obj do
assert(k * k == v)
end
```
The default iteration order for tables is specified to be consecutive for elements `1..#t` and unordered after that, visiting every element; similarly to iteration using `pairs`, modifying the table entries for keys other than the current one results in unspecified behavior.