Question

Factor appears to have a main method like any C-based language:

#! /usr/bin/env factor -script

USE: io
IN: hello

: hello ( -- ) "Hello World!" print ;

MAIN: hello

But Factor does not execute the main function automatically; if you run ./hello.factor in a terminal, nothing happens because main isn't called.

Does anyone know if Factor has syntax like Python, so that hello is actually called on ./hello.py?

def hello():
   print "Hello World!"

if __name__=="__main__":
   main()
Was it helpful?

Solution

Factor will now execute a main function if one is specified. You'll still have to edit ~/.factor-rc to add the INCLUDING/IN macros so that Factor will search for code in the current directory.

~/.factor-rc:

! Andrew Pennebaker
! INCLUDING macro that imports source code files in the current directory

USING: kernel vocabs.loader parser sequences lexer vocabs.parser ;
IN: syntax

: include-vocab ( vocab -- ) dup ".factor" append parse-file append use-vocab ;

SYNTAX: INCLUDING: ";" [ include-vocab ] each-token ;

scriptedmain.factor:

#! /usr/bin/env factor

USING: io math.parser ;
IN: scriptedmain

: meaning-of-life ( -- n ) 42 ;

: main ( -- ) meaning-of-life "Main: The meaning of life is " write number>string print ;

MAIN: main

test.factor:

#! /usr/bin/env factor

INCLUDING: scriptedmain ;
USING: io math.parser ;
IN: test

: main ( -- ) meaning-of-life "Test: The meaning of life is " write number>string print ;

MAIN: main

Example:

$ ./scriptedmain.factor Main: The meaning of life is 42 $ ./test.factor Test: The meaning of life is 42

As posted on RosettaCode.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top