Skip to content

[HOWTO] How Do I Do X with Red

Semseddin Moldibi edited this page Nov 30, 2022 · 1 revision

This is intended to be a collaborative list of how to perform common programming tasks with Red.

Use Help


Help Command

  • Display help about the help command help The help command is a very powerful tool. Typing help at the repl will display information about all of the things help can do for you. Some really important callouts:

    • help print will display information about the print function.

    • help "print" will display all functions which have the string "print" in them, or their descriptions. Notice the "!

    • ?? print will display the source code for the print function.

>> help
        Use HELP or ? to view built-in docs for functions, values 
	for contexts, or all values of a given datatype:

		help append
		? system
		? function!

	To search for values by name, use a word:

		? pri
		? to-

	To also search in function specs, use a string:

		? "pri"
		? "issue!"

	Other useful functions:

		??     - Display a word and the value it references
		probe  - Print a molded value
		source - Show a function's source code
		what   - Show a list of known functions or words
		about  - Display version number and build date
		quit   - Leave the Red console

Input and Output (IO)


Printing stuff

  • Print a value followed by a newline - print

>> print "Hello Red"
Hello Red
>> print ["2 x 2 =" 2 * 2]
2 x 2 = 4
  • Print a word and the value it refers to - ??

>> n: 42
== 42

>> ?? n
n: 42
  • Print something and return its value - probe

>> probe n
42
== 42

Reading stuff

  • Get console user input - input

>> i: input   ; set i to the value returned from the input function

hi
== "hi"
>> i
== "hi"
  • Get console user input with a prompt - ask

>> i: ask "Who are you? "
Who are you? ME
== "ME"
  • Read from a file, or url

>> read %day1.txt
== {1810^/1729^/1857^/1777^/1927^/1936^/1797^/1719^/1703^/1758^/1768^/2008^/1963^/1925^/1919^/...
>> read %Downloads/
== [%jdk-15.0.1_linux-x64_bin.deb %20201104_003631.jpg %20201107_105256.jpg %Ge...
>> read https://www.red-lang.org/p/getting-started.html
== {<!DOCTYPE html>^/<html class='v2' dir='ltr' xmlns='http://www.w3.org/1999/xh...
  • Read a specific line from a file - read/lines, pick

>> pick read/lines %day1.txt 42
== "1912"

help read in the Red console.

> help read
USAGE:
     READ source

DESCRIPTION: 
     Reads from a file, URL, or other port. 
     READ is an action! value.

ARGUMENTS:
     source       [file! url!] 

REFINEMENTS:
     /part        => Partial read a given number of units (source relative).
        length       [number!] 
     /seek        => Read from a specific position (source relative).
        index        [number!] 
     /binary      => Preserves contents exactly.
     /lines       => Convert to block of strings.
     /info        => 
     /as          => Read with the specified encoding, default is 'UTF-8.
        encoding     [word!] 

Writing stuff

  • Write to a File or URL

>> write %Hi.adoc "### Hello"
>> my-asciidoc: {
{    '''
{    * Write to a file
{    
{    ```red
{    write %Hi.adoc "### Hello"
{    ```
{    }
== {^/'''^/* Write to a file^/^/```red^/write %Hi.adoc "### Hello"^/```^/}
>> write/append %Hi.adoc my-asciidoc

help write in the Red console.

>> help write
USAGE:
     WRITE destination data

DESCRIPTION: 
     Writes to a file, URL, or other port. 
     WRITE is an action! value.

ARGUMENTS:
     destination  [file! url! port!] 
     data         [any-type!] 

REFINEMENTS:
     /binary      => Preserves contents exactly.
     /lines       => Write each value in a block as a separate line.
     /info        => 
     /append      => Write data at end of file.
     /part        => Partial write a given number of units.
        length       [number!] 
     /seek        => Write at a specific position.
        index        [number!] 
     /allow       => Specifies protection attributes.
        access       [block!] 
     /as          => Write with the specified encoding, default is 'UTF-8.
        encoding     [word!] 

Interogating stuff

  • Get the current directory

>> what-dir
== %/home/gt/
  • List the contents of the current directory

> list-dir %Downloads/
	jdk-15.0.1_linu...  	20201104_003631...  	20201107_105256...  
	Get_Programming...  
>> list-dir what-dir
	Pictures/           	.themes/            	tmp/                
	.profile            	red                 	.lazarus/           
	.gtkrc-xfce         	email               	HowDo.adoc          
	pm-tup.hs           	.sudo_as_admin_...  	Documents/    

help list-dir in the Red console.

>> help list-dir
USAGE:
     LIST-DIR dir

DESCRIPTION: 
     Displays a list of files and directories from given folder or current one. 
     LIST-DIR is a function! value.

ARGUMENTS:
     dir          [any-type!] "Folder to list."

REFINEMENTS:
     /col         => Forces the display in a given number of columns.
        n            [integer!] "Number of columns."
  • Get file size - size?

    From: https://rosettacode.org/wiki/File_size#Red
>> size? %input.txt
== 39244

>> size? %/c/input.txt
== 39244
  • Check if a file exists - exists?

> exists? %day1.txt
== true

>> exists? %some-file.txt
== false

Graphics (VID and View)

  • Create a Window (bare minimum)

view []
  • Create a Window with a title and size constraints

view [title "HAL 9000" size 800x600]

Start with VID for easy graphics: https://github.com/red/docs/blob/master/en/vid.adoc

Move to the View for more power: https://github.com/red/docs/blob/master/en/view.adoc

Have a look at Draw if you’re into drawing things: https://github.com/red/docs/blob/master/en/draw.adoc


  • A basic editor

view/options/flags [
	title "Basic Editor"
	editor: area 800x600 on-change [face/parent/actors/saved?: no]
][
	menu: ["File" ["Open" open "Save" save "Quit" quit]] 
	actors: object [
		on-menu: func [face event][
			switch event/picked [
				open [open-file face] 
				save [save-file] 
				quit [check-saving]
			]
		]
		on-close: does [check-saving]
		on-resizing: func [face event][
			editor/size: face/size - 20
		]
		on-resize: func [face event][on-resizing face none]
		check-saving: does [unless saved? [confirm] unview] ; or `quit` but this kills console too
		saved?: yes 
		file: none 
		open-file: func [face][
			if file: request-file [
				editor/text: read file
				face/text: form file
			]
		]
		save-file: does [
			file: any [file "New"]
			if file: request-file/save/file file [
				write file editor/text 
				saved?: yes
			]
		]
		confirm: does [
			view [
				title "Confirm"
				text "Save file?" return 
				button "Yes" [save-file unview] 
				button "No" [unview]
			]
		]
	]
] 'resize

Strings

  • Split a string - split

    >> split "abc,def,gh" #","
    == ["abc" "def" "gh"]
    
    >> split "Hello Red" space
    == ["Hello" "Red"]

help split in the Red console

  • Replace values in a string - replace

>> s: "Red is fun?"
== "Red is fun?"

>> replace s "?" "!"
== "Red is fun!"

>> replace/all "Mississippi" "i" "*"
== "M*ss*ss*pp*"

help replace in the Red console.

  • Remove whitespace or other pesky characters - trim

>> trim/all "one two three"
== "onetwothree"

>> trim/with "one two three" "t"
== "one two hree"

help trim in the Red console.

  • Convert a string (ex: file name) so it can be read by a browser - enhex

>> to file! enhex "0!  @#ok.png"
== %"0%21%20%20%40%23ok.png"

`help enhex ` in the Red console.

  • Parse a string


TBD

  • Install Red: https://www.red-lang.org/p/download.html

    • Use the REPL, play with Red, try red

    • Write a function

    • Include type specs for function args

    • Define an array/map/struct

    • Specify a datatype for a variable

  • Objects: https://www.red-lang.org/search?q=Object

    • Create an OOP class

    • Inherit from an object

    • Implement an OO interface

    • Create private/protected members in an object

    • Find out what methods an object or datatype supports


  • Find out what datatypes are available in Red, and how to use them

  • Enforce immutability

  • Pass values by reference or by value to functions

  • Create a lambda/anonymous function

  • Get the name of the function being called

  • Make HTTP requests (read URLs)

  • Access an API that uses JSON

  • Use command line arguments to Red scripts

  • Call/launch other programs, including redirecting I/O

  • Call C functions in DLLs

  • Convert Red/System values to the Red ones

  • Compile and cross compile

  • Import a library, load a module, use a package manager

  • Set the icon for an EXE

  • Use HTML in a Red GUI

  • Write Javascript code in Red

  • Include a web-browser component in a Red GUI

  • Do machine learning

  • Use regular expressions

Clone this wiki locally