Updated doc.

This commit is contained in:
Bruce Hill 2018-02-15 16:16:06 -08:00
parent 99c379870f
commit 1a06de84dd

View File

@ -55,25 +55,22 @@ DogSingleton = immutable(0, {name="DogSingleton", bark=function(self) print("woo
DogSingleton():bark()
```
## Tuple recipe
With immutable tables, it's pretty simple to emulate Python-like tuples:
## Tuples
If no field names are passed in, `immutable()` defaults to creating immutable tables that behave like Python's tuples:
```lua
local tuple_classes = {}
Tuple = function(...)
local n = select('#', ...)
if not tuple_classes[n] then
tuple_classes[n] = immutable(n)
end
return tuple_classes[n](...)
end
assert(Tuple(5,6,7) == Tuple(5,6,7))
assert(tostring(Tuple(8,9)) == "(8, 9)")
local Tuple = immutable()
local t0 = Tuple()
local t1 = Tuple(1,2)
local t2 = Tuple(1,2,3,4,5)
assert(t0 == Tuple())
assert(({[t1]='yep'})[Tuple(1,2)])
assert(tostring(Tuple(1,2)) == "(1, 2)")
```
## General purpose immutable table recipe
Using the tuple recipe above, you can make a function that returns an immutable version
of a table with arbitrary keys.
Using tuples, you can make a function that returns an immutable version of a table with arbitrary keys, though it is a little bit hacky.
```lua
local Tuple = immutable()
local immutable_classes = {}
Immutable = function(t)
local keys = {}