Skip to content

Instantly share code, notes, and snippets.

@hiiamboris
Last active September 3, 2022 18:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hiiamboris/167b13603359440dea4b6a444fdb0d88 to your computer and use it in GitHub Desktop.
Save hiiamboris/167b13603359440dea4b6a444fdb0d88 to your computer and use it in GitHub Desktop.
Simple typechecked object
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