Skip to content

Commit c0c7a37

Browse files
authored
Added LuaPairsIterable to language extensions (#88)
Co-authored-by: Tom <tomblind@users.noreply.github.com>
1 parent d38cb87 commit c0c7a37

File tree

1 file changed

+44
-4
lines changed

1 file changed

+44
-4
lines changed

docs/advanced/language-extensions.md

Lines changed: 44 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,29 @@ while (true) {
148148

149149
See the [Lua Reference Manual](https://www.lua.org/manual/5.3/manual.html#3.3.5) for more information on Lua for loops.
150150

151+
## LuaPairsIterable Type
152+
153+
Some types can be iterated with `pairs()` (for example, if the `__pairs` method is set in their metatable). These can be iterated without explicitly calling `pairs` by extending them from `LuaPairsIterable`.
154+
155+
<SideBySide>
156+
157+
```ts
158+
interface MyType extends LuaPairsIterable<number, string> {}
159+
declare const obj: MyType;
160+
161+
for (const [key, value] of obj) {
162+
console.log(key, value);
163+
}
164+
```
165+
166+
```lua
167+
for key, value in pairs(obj) do
168+
print(key, value)
169+
end
170+
```
171+
172+
</SideBySide>
173+
151174
## Operator Map Types
152175

153176
Lua supports overloading operators on types using [metatable methods](https://www.lua.org/manual/5.4/manual.html#2.4) such as `__add`. But, JavaScript and TypeScript do not support this. In order to use overloaded operators on types that support them, you can declare special mapping functions in TS that will translate to those operators in Lua.
@@ -286,7 +309,9 @@ print(#tbl)
286309

287310
### Iterating
288311

289-
To iterate over a `LuaTable`, use `pairs()`. (This requires the `lua-types` library to be installed.)
312+
To iterate over a `LuaTable`, use `for...of`. This will generate a `for...in` statement using `pairs()`.
313+
314+
<SideBySide>
290315

291316
```ts
292317
const tbl = new LuaTable<number, string>();
@@ -295,12 +320,27 @@ tbl.set(3, "bar");
295320
tbl.set(4, "bar");
296321
tbl.set(5, "bar");
297322

298-
for (const [key, value] of pairs(tbl)) {
299-
print(key);
300-
print(value);
323+
for (const [key, value] of tbl) {
324+
console.log(key);
325+
console.log(value);
301326
}
302327
```
303328

329+
```lua
330+
tbl = {}
331+
332+
tbl[3] = "bar"
333+
tbl[4] = "bar"
334+
tbl[5] = "bar"
335+
336+
for key, value in pairs(tbl) do
337+
print(key)
338+
print(value)
339+
end
340+
```
341+
342+
</SideBySide>
343+
304344
(Remember that in Lua, `pairs()` returns the keys in a random order.)
305345

306346
### Custom Getters and Setters

0 commit comments

Comments
 (0)