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
## Changes
Adds a section for table.freeze. This covers shallow and deep freezes.
## Checks
By submitting your pull request for review, you agree to the following:
- [x] This contribution was created in whole or in part by me, and I
have the right to submit it under the terms of this repository's open
source licenses.
- [x] I understand and agree that this contribution and a record of it
are public, maintained indefinitely, and may be redistributed under the
terms of this repository's open source licenses.
- [x] To the best of my knowledge, all proposed changes are accurate.
Copy file name to clipboardExpand all lines: content/en-us/luau/tables.md
+57Lines changed: 57 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -326,3 +326,60 @@ local original = {
326
326
327
327
localclone=deepCopy(original)
328
328
```
329
+
330
+
## Freezing Tables
331
+
332
+
Freezing a table makes it read-only. This means that its keys can't be written to, but can be read. New keys can't be created after a table is frozen. You can check if a table is frozen by using the `Library.table.isfrozen()` method. This feature is used to create constant values which you don't want to change.
333
+
334
+
### Shallow Freezes
335
+
336
+
To freeze a table without any nested tables, Luau offers the `Library.table.freeze()` method.
337
+
338
+
```lua
339
+
localtarget= {
340
+
key="value",
341
+
engine="Roblox",
342
+
playerID=505306092
343
+
}
344
+
345
+
table.freeze(target)
346
+
target.playerID=1--> attempt to modify a readonly table
347
+
```
348
+
349
+
### Deep Freezes
350
+
351
+
To freeze a more complex table with nested tables inside it, you'll need to use a recursive function similar to the following:
352
+
353
+
```lua
354
+
localfunctiondeepFreeze(target)
355
+
-- Shallow freeze the table
356
+
table.freeze(target)
357
+
358
+
-- Check each key of the table and freeze it if it's a table
359
+
for_, vintargetdo
360
+
iftype(v) =="table" then
361
+
deepFreeze(v)
362
+
end
363
+
end
364
+
end
365
+
```
366
+
367
+
With the function in place, you can deep freeze a table as follows:
368
+
369
+
```lua
370
+
localtarget= {
371
+
key="value",
372
+
playerInfo= {
373
+
playerID=505306092,
374
+
playerName="PlayerName"
375
+
},
376
+
otherInfo= {
377
+
{
378
+
{1, 3, 5, 7, 9}
379
+
}
380
+
}
381
+
}
382
+
383
+
deepFreeze(target)
384
+
target.playerInfo.playerID=1--> attempt to modify a readonly table
0 commit comments