Skip to content

Instantly share code, notes, and snippets.

@GiuseppeChillemi
Last active October 8, 2024 02:42
Show Gist options
  • Save GiuseppeChillemi/afa67bf2b87e64dcf383100cdc45c357 to your computer and use it in GitHub Desktop.
Save GiuseppeChillemi/afa67bf2b87e64dcf383100cdc45c357 to your computer and use it in GitHub Desktop.
Include-Function.red
Red [
Title: "Include a Function from a file"
Description: "Extracts and load one or more functions from a file"
]
copy-function: func [
"Search for a function definition and copy it from a block"
file [block!] "A block containing the functions"
name [word! set-word!] "The function name to search"
/local
s
e
parse-result
] [
name: append copy [quote] name
parse-result: parse file [
any
[
[s: quote set name ['func block! block! | 'function block! block! | 'does block! | 'do block!] break ]
|
[s: name [quote func block! block! | quote function block! block! | quote does block! | quote do block!] break ]
|
skip
]
e:
to end
]
either parse-result [copy/part at file index? s e] [none]
]
include-function: func [
"Searches and load a function"
file [file!] "The file to load"
name [word! set-word! block!] "One or more functions to load"
/local
fn
loaded-file
] [
loaded-file: attempt [load file]
either all [loaded-file block? loaded-file not empty? loaded-file] [
unless block? name [name: append copy [] name]
forall name [
either any [word? name/1 set-word? name/1] [
fn: copy-function loaded-file name/1
either not fn [
do make error! rejoin ["Function Name not found: " name]
] [
; Print "Including" probe fn ;Uncomment to DEBUG
do fn
]
] [
do make error! rejoin ["Function Name is not set-word! or word! " name]
]
]
] [
do make error! rejoin ["Invalid file: " file]
]
]
;Usage: include-function %filename function-name (or [function1 function2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment