Last active
September 3, 2022 18:13
-
-
Save hiiamboris/167b13603359440dea4b6a444fdb0d88 to your computer and use it in GitHub Desktop.
Simple typechecked object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Red [] | |
allow-types: function [word [any-word!] types [block!]] [ | |
obj: context? word | |
map: third find body-of :obj/on-change* 'type-checker | |
put map word func reduce [to word! word types] [] | |
] | |
restrict: function [types [block!] 'word [set-word!] value [any-type!]] [ | |
allow-types word types | |
set word :value | |
] | |
typed-object!: make object! [ ; | |
on-change*: function [word [any-word!] old [any-type!] new [any-type!]] [ | |
type-checker: select #() word | |
word: bind word self ;@@ bind required for `set obj value` case | |
set-quiet word :old ;-- in case of type error, word must have the old value | |
type-checker :new | |
set-quiet word :new ;-- restore the new value if no error | |
] | |
] | |
typed-object: function [ | |
"Build an object with automatic typechecks" | |
spec [block!] | |
][ | |
body: find body-of :typed-object!/on-change* 'type-checker | |
body/3: copy body/3 ;@@ workaround for map never being copied | |
make typed-object! spec | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment