You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/advanced/language-extensions.md
+44-4Lines changed: 44 additions & 4 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -148,6 +148,29 @@ while (true) {
148
148
149
149
See the [Lua Reference Manual](https://www.lua.org/manual/5.3/manual.html#3.3.5) for more information on Lua for loops.
150
150
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`.
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)
286
309
287
310
### Iterating
288
311
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>
290
315
291
316
```ts
292
317
const tbl =newLuaTable<number, string>();
@@ -295,12 +320,27 @@ tbl.set(3, "bar");
295
320
tbl.set(4, "bar");
296
321
tbl.set(5, "bar");
297
322
298
-
for (const [key, value] ofpairs(tbl)) {
299
-
print(key);
300
-
print(value);
323
+
for (const [key, value] oftbl) {
324
+
console.log(key);
325
+
console.log(value);
301
326
}
302
327
```
303
328
329
+
```lua
330
+
tbl= {}
331
+
332
+
tbl[3] ="bar"
333
+
tbl[4] ="bar"
334
+
tbl[5] ="bar"
335
+
336
+
forkey, valueinpairs(tbl) do
337
+
print(key)
338
+
print(value)
339
+
end
340
+
```
341
+
342
+
</SideBySide>
343
+
304
344
(Remember that in Lua, `pairs()` returns the keys in a random order.)
0 commit comments