Skip to content

Commit c0a57c6

Browse files
authored
Add table.freeze section (#909)
## 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.
1 parent 2af6880 commit c0a57c6

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

content/en-us/luau/tables.md

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,3 +326,60 @@ local original = {
326326

327327
local clone = deepCopy(original)
328328
```
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+
local target = {
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+
local function deepFreeze(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 _, v in target do
360+
if type(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+
local target = {
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
385+
```

0 commit comments

Comments
 (0)