Modulinos: Difference between revisions

24,119 bytes added ,  4 months ago
m
m (→‎{{header|Wren}}: Minor tidy)
 
(89 intermediate revisions by 35 users not shown)
Line 1:
{{draft task|Basic language learning}}
It is useful to be able to execute a main() function only when a program is run directly. This is a central feature in programming scripts;. theA featurescript that behaves this way is called a [http://www.slideshare.net/brian_d_foy/advanced-modulinos ''scripted mainmodulino''].
 
Examples from [https://github.com/mcandre/scriptedmain GitHub].modulinos
 
Sometimes getting the [[ScriptName]] is required in order to determine when to run main().
 
Care when manipulating command line arguments, due to subtle exec security constraints that may or not be enforced on implicit argv[0]. https://ryiron.wordpress.com/2013/12/16/argv-silliness/
: ''This is still a draft task, and the current task description has caused mega confusion. See '''[[Talk:Scripted Main]]''' for numerous attempts to understand the task and to rewrite the task description.''
 
: ''This is still a draft task, and the current task description has caused mega confusion. See '''[[Talk:Modulinos]]''' for numerous attempts to understand the task and to rewrite the task description.''
 
: '''The task [[Executable library]] is written to replace this task.''' ''This task's future is in doubt as its aims are not clear enough.''
<br><br>
 
=={{header|11l}}==
<syntaxhighlight lang="11l">// life.11l
 
F meaning_of_life()
R ‘*’.code
 
:start:
print(‘Main: The meaning of life is ’meaning_of_life())</syntaxhighlight>
 
<syntaxhighlight lang="11l">// death.11l
 
print(‘Life means ’life:meaning_of_life()‘.’)
print(‘Death means nothing.’)</syntaxhighlight>
 
=={{header|AppleScript}}==
 
AppleScript's equivalent of a main() function is a <tt>run</tt> handler, which can be either implicit or explicit:
 
<syntaxhighlight lang="applescript">display dialog "Hello"</syntaxhighlight>
or
<syntaxhighlight lang="applescript">on run
display dialog "Hello"
end run</syntaxhighlight>
 
A <tt>run</tt> handler's only executed when the script containing it is explicity ''run'', either from another script or application or as an application in its own right. It's not executed when a script's simply loaded as a library, although it can subsequently be so in the unlikely event of this being desirable. Scripts saved as applications aren't recognised by the "Libraries" system introduced in Mac OS X 10.9, but can be loaded and/or run using the older <tt>load script</tt> and <tt>run script</tt> commands. Script code can tell if it's running in its own application or being executed by an external agent by comparing its file path with that of the agent:
 
<syntaxhighlight lang="applescript">on run
if ((path to me) = (path to current application)) then
display dialog "I'm running in my own application."
else
display dialog "I'm being run from another script or application."
end if
end run</syntaxhighlight>
 
=={{header|Arturo}}==
 
===Library===
 
<syntaxhighlight lang="rebol">; modulinos - library
meaningOfLife: function [][
42
]
 
if standalone? ->
print ~"Library: The meaning of life is |meaningOfLife|"</syntaxhighlight>
 
{{out}}
 
<pre>Library: The meaning of life is 42</pre>
 
===Main===
 
<syntaxhighlight lang="rebol">do.import relative "modulinos - library.art"
print ~"Life means |meaningOfLife|."
print "Death means invisible scary skeletons."</syntaxhighlight>
 
{{out}}
 
<pre>Life means 42.
Death means invisible scary skeletons.</pre>
 
=={{header|C}}==
Line 14 ⟶ 80:
{{works with|GCC}}
 
C programs cannot normally do scripted main, because main() is implicitly included by another program, test.c, even though scriptedmain.h omits any main() prototype. AHowever, preprocessor instructions can hide main unless a compiler directiveflag is fixesexplicitly thisset.
 
Example
<lang sh>$ gcc -o scriptedmain scriptedmain.c scriptedmain.h
 
$ ./scriptedmain
<syntaxhighlight lang="sh">$ make
./scriptedmain
Main: The meaning of life is 42
./test
$ gcc -o test test.c scriptedmain.c scriptedmain.h
Test: The meaning of life is</syntaxhighlight>
$ ./test
 
Test: The meaning of life is 42</lang>
Makefile
 
<syntaxhighlight lang="make">all: scriptedmain test
./scriptedmain
./test
 
scriptedmain: scriptedmain.c scriptedmain.h
gcc -o scriptedmain -DSCRIPTEDMAIN scriptedmain.c scriptedmain.h
 
test: test.c scriptedmain.h scriptedmain.c
gcc -o test test.c scriptedmain.c scriptedmain.h
 
clean:
-rm scriptedmain
-rm test
-rm scriptedmain.exe
-rm test.exe</syntaxhighlight>
 
scriptedmain.h
 
<syntaxhighlight lang ="c">int meaning_of_life();</langsyntaxhighlight>
 
scriptedmain.c
 
<langsyntaxhighlight lang="c">#include <stdio.h>
 
int meaning_of_life() {
Line 35 ⟶ 120:
}
 
#ifdef SCRIPTEDMAIN
int __attribute__((weak)) main(int argc, char **argv) {
 
int main() {
printf("Main: The meaning of life is %d\n", meaning_of_life());
 
return 0;
}
}</lang>
 
#endif</syntaxhighlight>
 
test.c
 
<langsyntaxhighlight lang="c">#include "scriptedmain.h"
#include <stdio.h>
 
Line 51 ⟶ 140:
printf("Test: The meaning of life is %d\n", meaning_of_life());
return 0;
}</langsyntaxhighlight>
 
=={{header|C++}}==
C++ programs cannot normally do scripted main, because main() is implicitly included by another program, test.c, even though scriptedmain.h omits any main() prototype. APreprocessor instructions can hide main() unless a compiler directiveflat is fixesexplicitly thisset.
 
Example
 
<syntaxhighlight lang="sh">$ make
./scriptedmain
Main: The meaning of life is 42
./test
Test: The meaning of life is 42</syntaxhighlight>
 
Makefile
 
<syntaxhighlight lang="make">all: scriptedmain test
./scriptedmain
./test
 
scriptedmain: scriptedmain.cpp scriptedmain.h
g++ -o scriptedmain -static-libgcc -static-libstdc++ -DSCRIPTEDMAIN scriptedmain.cpp scriptedmain.h
 
test: test.cpp scriptedmain.h scriptedmain.cpp
g++ -o test -static-libgcc -static-libstdc++ test.cpp scriptedmain.cpp scriptedmain.h
 
clean:
-rm scriptedmain
-rm test
-rm scriptedmain.exe
-rm test.exe</syntaxhighlight>
 
scriptedmain.h
 
<syntaxhighlight lang ="cpp">int meaning_of_life();</langsyntaxhighlight>
 
scriptedmain.cpp
 
<langsyntaxhighlight lang="cpp">#include <iostream>
 
using namespace std;
Line 70 ⟶ 185:
}
 
#ifdef SCRIPTEDMAIN
int __attribute__((weak)) main(int argc, char **argv) {
cout << "Main: The meaning of life is " << meaning_of_life() << endl;
 
int main() {
cout << "Main: The meaning of life is " << meaning_of_life() << endl;
return 0;
}
}</lang>
 
#endif</syntaxhighlight>
 
test.cpp
 
<langsyntaxhighlight lang="cpp">#include "scriptedmain.h"
#include <iostream>
 
Line 85 ⟶ 203:
extern int meaning_of_life();
 
int main(int argc, char **argv) {
cout << "Test: The meaning of life is " << meaning_of_life() << endl;
 
return 0;
}</langsyntaxhighlight>
 
=={{header|Chicken SchemeClojure}}==
Uses [https://github.com/kumarshantanu/lein-exec lein-exec].
Chicken Scheme has the {{{ -ss }}} flag for the interpreter, but compiled Chicken Scheme programs do not have scripted main unless the behavior is added manually to the code.
 
scriptedmain.scmclj:
<syntaxhighlight lang="clojure">":";exec lein exec $0 ${1+"$@"}
":";exit
 
(ns scriptedmain
<lang scheme>#!/bin/sh
(:gen-class))
#|
exec csi -ss $0 ${1+"$@"}
exit
|#
 
(defn meaning-of-life [] 42)
(use posix)
(require-extension srfi-1) ; lists
 
(defn -main [& args]
(define (meaning-of-life) 42)
(println "Main: The meaning of life is" (meaning-of-life)))
 
(when (.contains (first *command-line-args*) *source-path*)
(define (main args)
(apply -main (rest *command-line-args*)))</syntaxhighlight>
(display (format "Main: The meaning of life is ~a\n" (meaning-of-life)))
(exit))
 
test.clj:
(define (program)
<syntaxhighlight lang="clojure">":";exec lein exec $0 ${1+"$@"}
(if (string=? (car (argv)) "csi")
":";exit
(let ((s-index (list-index (lambda (x) (string-contains x "-s")) (argv))))
(if (number? s-index)
(cons 'interpreted (list-ref (argv) (+ 1 s-index)))
(cons 'unknown "")))
(cons 'compiled (car (argv)))))
 
(ns test
(if (equal? (car (program)) 'compiled)
(:gen-class))
(main (cdr (argv))))</lang>
 
(load-string (slurp "scriptedmain.clj"))
test.scm
 
(defn -main [& args]
<lang scheme>#!/bin/sh
(println "Test: The meaning of life is" (scriptedmain/meaning-of-life)))
#|
exec csi -ss $0 ${1+"$@"}
exit
|#
(define (main args)
(load "scriptedmain.scm")
(display (format "Test: The meaning of life is ~a\n" (meaning-of-life)))
(exit))</lang>
 
(when (.contains (first *command-line-args*) *source-path*)
=={{header|Clojure}}==
(apply -main (rest *command-line-args*)))</syntaxhighlight>
Clojure has a function -main which will run in only four cases.
 
=={{header|CoffeeScript}}==
# clj is passed the flag -m &lt;class&gt;. <lang sh>$ clj -m scriptedmain
scriptedmain.coffee:
Main: The meaning of life is 42
<syntaxhighlight lang="coffeescript">#!/usr/bin/env coffee
$ clj -m test
Test: The meaning of life is 42</lang>
# A shebang forces -m &lt;class&gt;. <lang sh>$ ./scriptedmain.clj
Main: The meaning of life is 42
$ ./test.clj
Test: The meaning of life is 42</lang>
# The compiled class is run. <lang sh>$ java -cp ~/Library/Clojure/lib/clojure.jar:. scriptedmain
Main: The meaning of life is 42
$ java -cp ~/Library/Clojure/lib/clojure.jar:. test
Test: The meaning of life is 42</lang>
# -main is explicitly called. <lang sh>
$ clj
user=> (load-file "scriptedmain.clj")
user=> (scriptedmain/-main)
Main: The meaning of life is 42
nil</lang>
 
meaningOfLife = () -> 42
scriptedmain.clj
 
exports.meaningOfLife = meaningOfLife
<lang lisp>":";exec clj -m `basename $0 .clj` $0 ${1+"$@"}
":";exit
 
main = () ->
(ns scriptedmain
console.log "Main: The meaning of life is " + meaningOfLife()
(:gen-class))
 
if not module.parent then main()</syntaxhighlight>
(defn meaning-of-life [] 42)
 
test.coffee:
(defn -main [& args]
<syntaxhighlight lang="coffeescript">#!/usr/bin/env coffee
(println "Main: The meaning of life is" (meaning-of-life)))</lang>
 
sm = require "./scriptedmain"
test.clj
 
console.log "Test: The meaning of life is " + sm.meaningOfLife()</syntaxhighlight>
<lang lisp>":";exec clj -m `basename $0 .clj` $0 ${1+"$@"}
":";exit
 
(ns test
(:gen-class))
 
(load "scriptedmain")
 
(defn -main [& args]
(println "Test: The meaning of life is" (scriptedmain/meaning-of-life)))</lang>
 
=={{header|Common Lisp}}==
Line 189 ⟶ 268:
~/.clisprc.lisp
 
<langsyntaxhighlight lang="lisp">;;; Play nice with shebangs
(set-dispatch-macro-character #\# #\!
(lambda (stream character n)
(declare (ignore character n))
(read-line stream nil nil t)
nil))</langsyntaxhighlight>
 
scriptedmain.lisp
 
<langsyntaxhighlight lang="lisp">#!/bin/sh
#|
exec clisp -q -q $0 $0 ${1+"$@"}
Line 228 ⟶ 307:
args
:test #'(lambda (x y) (search x y :test #'equalp)))
(main args)))</langsyntaxhighlight>
 
test.lisp
 
<langsyntaxhighlight lang="lisp">#!/bin/sh
#|
exec clisp -q -q $0 $0 ${1+"$@"}
Line 239 ⟶ 318:
 
(load "scriptedmain.lisp")
(format t "Test: The meaning of life is ~a~%" (meaning-of-life))</langsyntaxhighlight>
 
=={{header|D}}==
Line 247 ⟶ 326:
scriptedmain.d:
 
<langsyntaxhighlight lang="d">#!/usr/bin/env rdmd -version=scriptedmain
 
module scriptedmain;
Line 261 ⟶ 340:
writeln("Main: The meaning of life is ", meaningOfLife());
}
}</langsyntaxhighlight>
 
test.d:
 
<langsyntaxhighlight lang="d">#!/usr/bin/env rdmd -version=test
 
import scriptedmain;
Line 274 ⟶ 353:
writeln("Test: The meaning of life is ", meaningOfLife());
}
}</langsyntaxhighlight>
 
Example:
 
<langsyntaxhighlight lang="sh">$ ./scriptedmain.d
Main: The meaning of life is 42
$ ./test.d
Line 287 ⟶ 366:
$ dmd test.d scriptedmain.d -version=test
$ ./test
Test: The meaning of life is 42</langsyntaxhighlight>
 
=={{header|Dart}}==
scriptedmain.dart:
<syntaxhighlight lang="dart">#!/usr/bin/env dart
 
#library("scriptedmain");
 
meaningOfLife() {
return 42;
}
 
main() {
print("Main: The meaning of life is ${meaningOfLife()}");
}</syntaxhighlight>
 
test.dart:
<syntaxhighlight lang="dart">#!/usr/bin/env dart
 
#import("scriptedmain.dart", prefix: "scriptedmain");
 
main() {
print("Test: The meaning of life is ${scriptedmain.meaningOfLife()}");
}</syntaxhighlight>
 
Example:
<syntaxhighlight lang="sh">$ ./scriptedmain.dart
Main: The meaning of life is 42
$ ./test.dart
Test: The meaning of life is 42</syntaxhighlight>
 
=={{header|Emacs Lisp}}==
Line 294 ⟶ 402:
scriptedmain.el
 
<langsyntaxhighlight lang="lisp">:;exec emacs -batch -l $0 -f main $*
 
;;; Shebang from John Swaby
Line 302 ⟶ 410:
 
(defun main ()
(message "Main: The meaning of life is %d" (meaning-of-life)))</langsyntaxhighlight>
 
test.el
 
<langsyntaxhighlight lang="lisp">:;exec emacs -batch -l $0 -f main $*
 
;;; Shebang from John Swaby
Line 314 ⟶ 422:
(setq load-path (cons default-directory load-path))
(load "scriptedmain.el" nil t)
(message "Test: The meaning of life is %d" (meaning-of-life)))</langsyntaxhighlight>
 
=={{header|EMal}}==
{{trans|Wren}}
<syntaxhighlight lang="emal">
^|We have created a module named ModulinosPart.emal.
|^
in Org:RosettaCode
type ModulinosPart
fun meaningOfLife = int by block do return 42 end
fun main = void by block do writeLine("The meaning of life is " + meaningOfLife() + ".") end
if Runtime.direct() do main() end
</syntaxhighlight>
{{out}}
<pre>
emal.exe Org\RosettaCode\ModulinosPart.emal
The meaning of life is 42.
</pre>
<syntaxhighlight lang="emal">
^|Then we create a new module named Modulinos.emal,
|this imports the previous module.
|^
in Org:RosettaCode
load :ModulinosPart
type Modulinos
fun main = int by List args
writeLine("Who says the meaning of life is " + ModulinosPart.meaningOfLife() + "?")
return 0
end
exit main(Runtime.args)
</syntaxhighlight>
{{out}}
<pre>
emal.exe Org\RosettaCode\Modulinos.emal
Who says the meaning of life is 42?
</pre>
 
=={{header|Erlang}}==
Erlang has scripted main by default. scriptedmain.erl must be compiled before test.erl can access its functions.
 
Makefile:
scriptedmain.erl
<syntaxhighlight lang="make">all: t
 
<langt: erlang>-module(scriptedmain).beam test.beam
erl -noshell -s scriptedmain
-export([meaning_of_life/0]).
erl -noshell -s test
-import(lists, [map/2]).
 
scriptedmain.beam: scriptedmain.erl
meaning_of_life() -> 42.
erlc scriptedmain.erl
 
test.beam: test.erl
main(_) ->
erlc test.erl
io:format("Main: The meaning of life is ~w~n", [meaning_of_life()]).</lang>
 
clean:
test.erl
-rm *.beam</syntaxhighlight>
 
<lang erlang>% Compile scriptedmain.erl first.:
<syntaxhighlight lang="erlang">-module(scriptedmain).
-export([meaning_of_life/0, start/0]).
 
meaning_of_life() -> 42.
-module(test).
 
start() ->
io:format("Main: The meaning of life is ~w~n", [meaning_of_life()]),
init:stop().</syntaxhighlight>
 
test.erl:
<syntaxhighlight lang="erlang">-module(test).
-export([start/0]).
-import(scriptedmain, [meaning_of_life/0]).
 
mainstart(_) ->
io:format("Test: The meaning of life is ~w~n", [meaning_of_life()]).</lang>,
init:stop().</syntaxhighlight>
 
=={{header|F Sharp|F#}}==
 
Note 1: F# supports the scriptedmain behavior, but F# does not support hybrid script-compiled code files. The following programs work provided that they are compiled and then run, as .fs files, not interpreted or dotslashed as .fsx files.
 
Note 2: fsharpc has a backwards file ordering: Specify any dependencies BEFORE the code that depends on them.
 
Note 3: fsharpc also has that unpredictable DOS-flavored command line flag syntax, so the --out requires a colon between it and its value, and -h only generates an error; use --help instead.
 
Note 4: In Unix, mono is required to run F# executables. In Windows, mono is not required for execution.
 
Example:
 
<syntaxhighlight lang="sh">$ make
fsharpc --out:scriptedmain.exe ScriptedMain.fs
fsharpc --out:test.exe ScriptedMain.fs Test.fs
$ mono scriptedmain.exe
Main: The meaning of life is 42
$ mono test.exe
Test: The meaning of life is 42</syntaxhighlight>
 
Makefile:
 
<syntaxhighlight lang="make">all: scriptedmain.exe test.exe
 
scriptedmain.exe: ScriptedMain.fs
fsharpc --nologo --out:scriptedmain.exe ScriptedMain.fs
 
test.exe: Test.fs ScriptedMain.fs
fsharpc --nologo --out:test.exe ScriptedMain.fs Test.fs
 
clean:
-rm *.exe</syntaxhighlight>
 
ScriptedMain.fs:
 
<syntaxhighlight lang="fsharp">namespace ScriptedMain
 
module ScriptedMain =
let meaningOfLife = 42
 
let main =
printfn "Main: The meaning of life is %d" meaningOfLife</syntaxhighlight>
 
Test.fs:
 
<syntaxhighlight lang="fsharp">module Test =
open ScriptedMain
 
let main =
printfn "Test: The meaning of life is %d" ScriptedMain.meaningOfLife</syntaxhighlight>
 
=={{header|Factor}}==
Line 345 ⟶ 553:
Example:
 
<langsyntaxhighlight lang="sh">$ ./scriptedmain.factor
Main: The meaning of life is 42
$ ./test.factor
Test: The meaning of life is 42</langsyntaxhighlight>
 
~/.factor-rc:
 
<langsyntaxhighlight lang="factor">! INCLUDING macro that imports source code files in the current directory
 
USING: kernel vocabs.loader parser sequences lexer vocabs.parser ;
Line 359 ⟶ 567:
: include-vocab ( vocab -- ) dup ".factor" append parse-file append use-vocab ;
 
SYNTAX: INCLUDING: ";" [ include-vocab ] each-token ;</langsyntaxhighlight>
 
scriptedmain.factor:
 
<langsyntaxhighlight lang="factor">#! /usr/bin/env factor
 
USING: io math.parser ;
Line 372 ⟶ 580:
: main ( -- ) meaning-of-life "Main: The meaning of life is " write number>string print ;
 
MAIN: main</langsyntaxhighlight>
 
test.factor:
 
<langsyntaxhighlight lang="factor">#! /usr/bin/env factor
 
INCLUDING: scriptedmain ;
Line 384 ⟶ 592:
: main ( -- ) meaning-of-life "Test: The meaning of life is " write number>string print ;
 
MAIN: main</langsyntaxhighlight>
 
=={{header|Forth}}==
Line 390 ⟶ 598:
Given this awful running reference:
 
<langsyntaxhighlight lang="forth">42 constant Douglas-Adams
 
: go ( -- )
." The meaning of life is " Douglas-Adams . cr ;</langsyntaxhighlight>
 
The bulk of Forth systems provide a way to generate an executable that enters GO (ar any word) on start.
Line 399 ⟶ 607:
{{works with|SwiftForth|SwiftForth|4.0}}
 
<langsyntaxhighlight lang="forth">' go 'MAIN !
program douglas-adams</langsyntaxhighlight>
 
Which creates a file named 'douglas-adams' that you can then run. If this is all in the same file, you can load the file, test parts of it, and then exit (or shell out) to run the executable.
Line 408 ⟶ 616:
{{works with|gforth}}
 
<langsyntaxhighlight lang="forth">#! /usr/bin/env gforth
 
42 constant Douglas-Adams
.( The meaning of life is ) Douglas-Adams . cr bye</langsyntaxhighlight>
 
Adding #! as a comment, as gforth does, is trivial. For a means by which this script could distinguish between 'scripted execution' and otherwise, a symlink like 'forthscript' could easily be used, and the zeroth OS argument tested for, but there's no convention.
Line 417 ⟶ 625:
{{works with|gforth}}
 
<langsyntaxhighlight lang="forth">#! /usr/bin/env forthscript
 
42 constant Douglas-Adams
Line 425 ⟶ 633:
[THEN]
 
cr .( Why aren't you running this as a script? It only provides a constant.)</langsyntaxhighlight>
 
=={{header|Free Pascal}}==
 
=={{header|FreeBASIC}}==
Makefile:
{{trans|Ring}}
<syntaxhighlight lang="freebasic">
Function meaningoflife() As Byte
Dim As Byte y = 42
Return y
End Function
 
Sub main()
<lang make>all: scriptedmain
Print "Main: The meaning of life is "; meaningoflife()
End Sub
 
main()
scriptedmain: scriptedmain.pas
Sleep
fpc -dscriptedmain scriptedmain.pas
</syntaxhighlight>
{{out}}
<pre>
Main: The meaning of life is 42
</pre>
 
test: test.pas scriptedmain
fpc test.pas
 
=={{header|Go}}==
clean:
Go doesn't support scripted main directly.
-rm test
-rm scriptedmain
-rm *.o
-rm *.ppu</lang>
 
Although the [https://github.com/mcandre/modulinos examples] linked to above include an example for Go, this is only a work around, not an emulation. To emulate a modulino, we need to proceed as in the [[https://rosettacode.org/wiki/Executable_library#Go Executable library]] task and split the 'main' package into two.
scriptedmain.pas:
 
First create these two files in the 'modulino' directory:
<lang pascal>{$IFDEF scriptedmain}
<syntaxhighlight lang="go">// modulino.go
program ScriptedMain;
package main
{$ELSE}
unit ScriptedMain;
interface
function MeaningOfLife () : integer;
implementation
{$ENDIF}
function MeaningOfLife () : integer;
begin
MeaningOfLife := 42
end;
{$IFDEF scriptedmain}
begin
write('Main: The meaning of life is: ');
writeln(MeaningOfLife())
{$ENDIF}
end.</lang>
 
import "fmt"
test.pas:
 
func MeaningOfLife() int {
<lang pascal>program Test;
return 42
uses
}
ScriptedMain;
begin
write('Test: The meaning of life is: ');
writeln(MeaningOfLife())
end.</lang>
 
func libMain() {
Example:
fmt.Println("The meaning of life is", MeaningOfLife())
}</syntaxhighlight>
 
<syntaxhighlight lang="go">// modulino_main.go
<lang sh>$ make
package main
$ ./scriptedmain
Main: The meaning of life is: 42
func main() {
$ make test
libMain()
$ ./test
}</syntaxhighlight>
Test: The meaning of life is: 42</lang>
 
To emulate a modulino:
=={{header|Go}}==
{{out}}
<pre>
$ go run modulino
 
The meaning of life is 42
Makefile:
</pre>
 
Now create this file in the 'mol' directory:
<lang make>include $(GOROOT)/src/Make.inc
<syntaxhighlight lang="go">// mol.go
TARG=scriptname
package main
GOFILES=scriptname.go
include $(GOROOT)/src/Make.cmd</lang>
 
import "fmt"
scriptname.go:
 
<lang go>package main
import ("os"; "fmt")
func main() {
fmt.Println("The meaning of life is still", MeaningOfLife())
program := os.Args[0]
}</syntaxhighlight>
fmt.Println("Program:", program)
and copy modulino.go to the 'mol' directory. The library can then be used in the 'normal' way:
}</lang>
{{out}}
<pre>
$ go run mol
 
The meaning of life is still 42
</pre>
 
=={{header|Groovy}}==
 
Example:
 
<syntaxhighlight lang="sh">$ ./ScriptedMain.groovy
Main: The meaning of life is 42
$ ./Test.groovy
Test: The meaning of life is 42</syntaxhighlight>
 
ScriptedMain.groovy:
 
<syntaxhighlight lang="groovy">#!/usr/bin/env groovy
 
class ScriptedMain {
static def meaningOfLife = 42
 
static main(args) {
println "Main: The meaning of life is " + meaningOfLife
}
}</syntaxhighlight>
 
Test.groovy:
 
<syntaxhighlight lang="groovy">#!/usr/bin/env groovy
 
println "Test: The meaning of life is " + ScriptedMain.meaningOfLife</syntaxhighlight>
 
=={{header|Haskell}}==
Haskell has scripted main, but getting scripted main to work with compiled scripts is tricky.
 
<langsyntaxhighlight lang="sh">$ runhaskell scriptedmain.hs
Main: The meaning of life is 42
$ runhaskell test.hs
Line 517 ⟶ 747:
$ ghc -fforce-recomp -o test -main-is Test test.hs scriptedmain.hs
$ ./test
Test: The meaning of life is 42</langsyntaxhighlight>
 
scriptedmain.hs
 
<langsyntaxhighlight lang="haskell">#!/usr/bin/env runhaskell
 
-- Compile:
Line 533 ⟶ 763:
 
main :: IO ()
main = putStrLn $ "Main: The meaning of life is " ++ show meaningOfLife</langsyntaxhighlight>
 
test.hs
 
<langsyntaxhighlight lang="haskell">#!/usr/bin/env runhaskell
 
-- Compile:
Line 548 ⟶ 778:
 
main :: IO ()
main = putStrLn $ "Test: The meaning of life is " ++ show meaningOfLife</langsyntaxhighlight>
 
=={{header|Io}}==
Line 554 ⟶ 784:
ScriptedMain.io:
 
<langsyntaxhighlight lang="io">#!/usr/bin/env io
 
ScriptedMain := Object clone
ScriptedMain meaningOfLife := 42
 
if( isLaunchScript,
main := method(
"Main: The meaning of life is #{ScriptedMain meaningOfLife}" interpolate println
)</syntaxhighlight>
)
 
if (System args size > 0 and System args at(0) containsSeq("ScriptedMain"), main)</lang>
 
test.io:
 
<langsyntaxhighlight lang="io">#!/usr/bin/env io
 
main := method(
"Test: The meaning of life is #{ScriptedMain meaningOfLife}" interpolate println
)
 
"Test: The meaning of life is #{ScriptedMain meaningOfLife}" interpolate println</syntaxhighlight>
if (System args size > 0 and System args at(0) containsSeq("test"), main)</lang>
 
<langsyntaxhighlight lang="sh">$ ./ScriptedMain.io
Main: The meaning of life is 42
$ ./test.io
Test: The meaning of life is 42</langsyntaxhighlight>
 
=={{header|J}}==
 
modulinos.ijs:
scriptedmain.j:
 
<lang j>#!/usr/bin/env jconsole
 
load 'regex'
 
<syntaxhighlight lang="j">#!/usr/bin/env ijconsole
meaningOfLife =: 42
 
main =: monad : 0define
echo 'Main: The meaning of life is ', > 'd' (8!":0) meaningOfLife
exit ''
)
 
programshouldrun =: monad : 0define
if. (#;.1 ARGV)e. >'modulinos.ijs' 0E. ;ARGV do.
> 1 { ARGV
else.
'Interpreted'
end.
)
 
shouldrun =: monad : 0
if. '.*scriptedmain.*' rxeq program 0 do.
main 0
end.
)
 
shouldrun 0</langsyntaxhighlight>
 
test.j:
 
<langsyntaxhighlight lang="j">#!/usr/bin/env jconsole
 
load 'scriptedmainmodulinos.jijs'
 
echo 'Test: The meaning of life is ', > 'd' (8!":0) meaningOfLife
 
exit ''</langsyntaxhighlight>
 
Example:
 
<langsyntaxhighlight lang="sh">$ ./scriptedmainmodulinos.jijs
Main: The meaning of life is 42
$ ./test.j
Test: The meaning of life is 42</langsyntaxhighlight>
 
=={{header|Java}}==
Line 633 ⟶ 847:
ScriptedMain.java
 
<langsyntaxhighlight lang="java">public class ScriptedMain {
public static int meaningOfLife() {
return 42;
Line 641 ⟶ 855:
System.out.println("Main: The meaning of life is " + meaningOfLife());
}
}</langsyntaxhighlight>
 
Test.java
 
<langsyntaxhighlight lang="java">public class Test {
public static void main(String[] args) {
System.out.println("Test: The meaning of life is " + ScriptedMain.meaningOfLife());
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
{{Works with|Node.js}}
Node.js has scripted main.
 
scriptedmain.js
<syntaxhighlight lang="javascript">#!/usr/bin/env node
 
function meaningOfLife() { return 42; }
 
exports.meaningOfLife = meaningOfLife;
 
function main() {
console.log("Main: The meaning of life is " + meaningOfLife());
}
 
if (!module.parent) { main(); }</syntaxhighlight>
 
test.js
<syntaxhighlight lang="javascript">#!/usr/bin/env node
 
var sm = require("./scriptedmain");
 
console.log("Test: The meaning of life is " + sm.meaningOfLife());</syntaxhighlight>
 
=={{header|Julia}}==
Julia does not use scripted main by default, but can be set to run as such. Modules generally use a /test unit test subdirectory instead.
<br />
In module file Divisors.jl:
<syntaxhighlight lang="julia">module Divisors
 
using Primes
 
export properdivisors
 
function properdivisors(n::T) where T <: Integer
0 < n || throw(ArgumentError("number to be factored must be ≥ 0, got $n"))
1 < n || return T[]
!isprime(n) || return T[one(T), n]
f = factor(n)
d = T[one(T)]
for (k, v) in f
c = T[k^i for i in 0:v]
d = d*c'
d = reshape(d, length(d))
end
sort!(d)
return d[1:end-1]
end
 
function interactiveDivisors()
println("\nFind proper divisors between two numbers.\nFirst number: ")
lo = (x = tryparse(Int64, readline())) == nothing ? 0 : x
println("\nSecond number: ")
hi = (x = tryparse(Int64, readline())) == nothing ? 10 : x
lo, hi = lo > hi ? (hi, lo) : (lo, hi)
 
println("Listing the proper divisors for $lo through $hi.")
for i in lo:hi
println(lpad(i, 7), " => ", rpad(properdivisors(i), 10))
end
end
 
end
 
# some testing code
if occursin(r"divisors.jl"i, Base.PROGRAM_FILE)
println("This module is running as main.\n")
Divisors.interactiveDivisors()
end
</syntaxhighlight>
In a user file getdivisors.jl:
<syntaxhighlight lang="julia">include("divisors.jl")
 
using .Divisors
 
n = 708245926330
println("The proper divisors of $n are ", properdivisors(n))
</syntaxhighlight>
 
=={{header|LLVM}}==
LLVM can have scripted main a la C, using the weak attribute.
 
<langsyntaxhighlight lang="sh">$ make
llvm-as scriptedmain.ll
llc scriptedmain.bc
Line 664 ⟶ 957:
gcc -o test test.s scriptedmain.s
./test
Test: The meaning of life is 42</langsyntaxhighlight>
 
Makefile
 
<langsyntaxhighlight lang="make">EXECUTABLE_SM=scriptedmain
EXECUTABLE_TEST=test
 
Line 689 ⟶ 982:
-rm test.bc
-rm scriptedmain.s
-rm scriptedmain.bc</langsyntaxhighlight>
 
scriptedmain.ll
 
<langsyntaxhighlight lang="llvm">@msg_main = internal constant [33 x i8] c"Main: The meaning of life is %d\0A\00"
 
declare i32 @printf(i8* noalias nocapture, ...)
Line 707 ⟶ 1,000:
 
ret i32 0
}</langsyntaxhighlight>
 
test.ll
 
<langsyntaxhighlight lang="llvm">@msg_test = internal constant [33 x i8] c"Test: The meaning of life is %d\0A\00"
 
declare i32 @printf(i8* noalias nocapture, ...)
Line 723 ⟶ 1,016:
 
ret i32 0
}</langsyntaxhighlight>
 
=={{header|Lua}}==
Line 730 ⟶ 1,023:
scriptedmain.lua
 
<langsyntaxhighlight lang="lua">#!/usr/bin/env lua
 
function meaningoflife()
Line 744 ⟶ 1,037:
else
module(..., package.seeall)
end</langsyntaxhighlight>
 
test.lua
 
<langsyntaxhighlight lang="lua">#!/usr/bin/env lua
sm = require("scriptedmain")
print("Test: The meaning of life is " .. sm.meaningoflife())</langsyntaxhighlight>
 
=={{header|MathematicaMake}}==
 
Example
<syntaxhighlight lang="sh">$ make -f scriptedmain.mf
The meaning of life is 42
(Main)
$ make -f test.mf
The meaning of life is 42
(Test)</syntaxhighlight>
 
scriptedmain.mf
<syntaxhighlight lang="make">all: scriptedmain
 
meaning-of-life:
@echo "The meaning of life is 42"
 
scriptedmain: meaning-of-life
@echo "(Main)"
</syntaxhighlight>
 
test.mf
<syntaxhighlight lang="make">all: test
 
test:
@make -f scriptedmain.mf meaning-of-life
@echo "(Test)"
</syntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
 
scriptedmain.ma
<langsyntaxhighlight lang="mathematica">#!/usr/bin/env MathKernel -script
 
MeaningOfLife[] = 42
Line 770 ⟶ 1,091:
If[StringMatchQ[Program, ".*scriptedmain.*"],
Print["Main: The meaning of life is " <> ToString[MeaningOfLife[]]]
]</langsyntaxhighlight>
 
test.ma:
<langsyntaxhighlight lang="mathematica">#!/usr/bin/env MathKernel -script
 
Get["scriptedmain.ma"]
 
Print["Test: The meaning of life is " <> ToString[MeaningOfLife[]]]</langsyntaxhighlight>
 
Example:
<langsyntaxhighlight lang="sh">$ ./scriptedmain.ma
Main: The meaning of life is 42
$ ./test.ma
Test: The meaning of life is 42</langsyntaxhighlight>
 
In Mac and Windows, the output will be surrounded by spurious quotes.
 
=={{header|Mozart/Oz}}==
Makefile:
<syntaxhighlight lang="make">all: run
 
run: scriptedmain test
./scriptedmain
./test
 
scriptedmain: scriptedmain.oz
ozc -x scriptedmain.oz
 
scriptedmain.ozf: scriptedmain.oz
ozc -c scriptedmain.oz
 
test: scriptedmain.ozf test.oz
ozc -x test.oz
 
clean:
-rm test
-rm scriptedmain
-rm *.ozf
-rm *.exe
</syntaxhighlight>
 
scriptedmain.oz:
<syntaxhighlight lang="oz">functor
export
meaningOfLife: MeaningOfLife
import
System
Application
Property
Regex at 'x-oz://contrib/regex'
define
fun {MeaningOfLife} 42 end
 
local ScriptName = {Property.get 'application.url'} in
if {Regex.search "scriptedmain" ScriptName} \= false then
{System.printInfo "Main: The meaning of life is "#{Int.toString {MeaningOfLife}}#"\n"}
{Application.exit 0}
end
end
end
</syntaxhighlight>
 
test.oz:
<syntaxhighlight lang="oz">functor
import
ScriptedMain
System
Application
Property
Regex at 'x-oz://contrib/regex'
define
local ScriptName = {Property.get 'application.url'} in
if {Regex.search "test" ScriptName} \= false then
{System.printInfo "Test: The meaning of life is "#{Int.toString {ScriptedMain.meaningOfLife}}#"\n"}
{Application.exit 0}
end
end
end</syntaxhighlight>
 
=={{header|newLISP}}==
Line 792 ⟶ 1,175:
scriptedmain.lsp
 
<langsyntaxhighlight lang="lisp">#!/usr/bin/env newlisp
 
(context 'SM)
Line 804 ⟶ 1,187:
(if (find "scriptedmain" (main-args 1)) (main))
 
(context MAIN)</langsyntaxhighlight>
 
test.lsp
 
<langsyntaxhighlight lang="lisp">#!/usr/bin/env newlisp
 
(load "scriptedmain.lsp")
(println (format "Test: The meaning of life is %d" (SM:meaning-of-life)))
(exit)</langsyntaxhighlight>
 
=={{header|Node.jsNim}}==
Nim provides the predicate <code>isMainModule</code> to use with conditional compilation. Here is an example:
Node.js has scripted main.
 
<syntaxhighlight lang="Nim">proc p*() =
scriptedmain.js
## Some exported procedure.
echo "Executing procedure"
 
# Some code to execute to initialize the module.
<lang javascript>#!/usr/bin/env node
echo "Initializing the module"
 
when isMainModule:
function meaningOfLife() { return 42; }
# Some code to execute if the module is run directly, for instance code to test the module.
 
echo "Running tests"
exports.meaningOfLife = meaningOfLife;
</syntaxhighlight>
 
function main() {
console.log("Main: The meaning of life is " + meaningOfLife());
}
 
{{out}}
if (!module.parent) { main(); }</lang>
When run directly, the result of execution is:
 
<pre>Initializing the module
test.js
Running tests
 
</pre>
<lang javascript>#!/usr/bin/env node
If we call “p” from another module, we get:
 
<pre>Initializing the module
var sm = require("./scriptedmain");
Executing procedure
 
</pre>
console.log("Test: The meaning of life is " + sm.meaningOfLife());</lang>
 
=={{header|Objective-C}}==
Line 843 ⟶ 1,226:
scriptedmain.h:
 
<langsyntaxhighlight lang="objc">#import <objc/Object.h>
 
@interface ScriptedMain: Object {}
Line 849 ⟶ 1,232:
+ (int)meaningOfLife;
 
@end</langsyntaxhighlight>
 
scriptedmain.m:
 
<langsyntaxhighlight lang="objc">#import "scriptedmain.h"
#import <Foundation/Foundation.h>
 
Line 865 ⟶ 1,248:
 
int __attribute__((weak)) main(int argc, char **argv) {
@autoreleasepool {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 
printf("Main: The meaning of life is %d\n", [ScriptedMain meaningOfLife]);
 
}
[pool drain];
 
return 0;
}</langsyntaxhighlight>
 
test.m:
 
<langsyntaxhighlight lang="objc">#import "scriptedmain.h"
#import <Foundation/Foundation.h>
 
int main(int argc, char **argv) {
@autoreleasepool {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 
printf("Test: The meaning of life is %d\n", [ScriptedMain meaningOfLife]);
 
}
[pool drain];
 
return 0;
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="sh">$ gcc -o scriptedmain -lobjc -framework foundation scriptedmain.m
$ gcc -o test -lobjc -framework foundation test.m scriptedmain.m
$ ./scriptedmain
Main: The meaning of life is 42
$ ./test
Test: The meaning of life is 42</langsyntaxhighlight>
 
=={{header|OCaml}}==
Line 900 ⟶ 1,283:
scriptedmain.ml
 
<syntaxhighlight lang="ocaml">let meaning_of_life = 42
<lang ocaml>(*
 
let main () =
Compile:
Printf.printf "Main: The meaning of life is %d\n"
meaning_of_life
 
let () =
ocamlc -o scriptedmain -linkall str.cma scriptedmain.ml
if not !Sys.interactive then
main ()</syntaxhighlight>
 
Invoked as a script:
Run:
 
./<syntaxhighlight lang="sh">$ ocaml scriptedmain.ml
Main: The meaning of life is 42</syntaxhighlight>
 
*)
 
let meaning_of_life : int = 42
 
let main () = print_endline ("Main: The meaning of life is " ^ string_of_int meaning_of_life)
 
Loaded into an ocaml toplevel/utop:
let _ =
let program = Sys.argv.(0)
and re = Str.regexp "scriptedmain" in
try let _ = Str.search_forward re program 0 in
main ()
with Not_found -> ()</lang>
 
<syntaxhighlight lang="text">$ ocaml
test.ml
...
# #use "scriptedmain.ml";;
val meaning_of_life : int = 42
val main : unit -> unit = <fun>
# meaning_of_life;;
- : int = 42
# </syntaxhighlight>
 
The limit of this technique is "avoiding running something when loading a script interactively". It's not applicable to other uses, like adding an example script to a file normally used as a library, as that code will also fire when users of the library are run.
<lang ocaml>(*
 
Compile:
 
ocamlc -o test -linkall str.cma scriptedmain.ml test.ml
 
Run:
 
./test
 
*)
 
let main () = print_endline ("Test: The meaning of life is " ^ string_of_int Scriptedmain.meaning_of_life)
 
let _ =
let program = Sys.argv.(0)
and re = Str.regexp "test" in
try let _ = Str.search_forward re program 0 in
main ()
with Not_found -> ()</lang>
 
=={{header|Octave}}/{{header|MATLAB}}==
Line 951 ⟶ 1,316:
meaningoflife.m
 
<langsyntaxhighlight lang="matlab">#!/usr/bin/env octave -qf
 
function y = meaningoflife()
Line 961 ⟶ 1,326:
endfunction
 
main();</langsyntaxhighlight>
 
test.m
 
<langsyntaxhighlight lang="matlab">#!/usr/bin/env octave -qf
 
printf("Test: The meaning of life is %d", meaningoflife());</langsyntaxhighlight>
 
=={{header|Pascal}}==
{{works with|Free_Pascal}}
Makefile:
 
<syntaxhighlight lang="make">all: scriptedmain
 
scriptedmain: scriptedmain.pas
fpc -dscriptedmain scriptedmain.pas
 
test: test.pas scriptedmain
fpc test.pas
 
clean:
-rm test
-rm scriptedmain
-rm *.o
-rm *.ppu</syntaxhighlight>
 
scriptedmain.pas:
 
<syntaxhighlight lang="pascal">{$IFDEF scriptedmain}
program ScriptedMain;
{$ELSE}
unit ScriptedMain;
interface
function MeaningOfLife () : integer;
implementation
{$ENDIF}
function MeaningOfLife () : integer;
begin
MeaningOfLife := 42
end;
{$IFDEF scriptedmain}
begin
write('Main: The meaning of life is: ');
writeln(MeaningOfLife())
{$ENDIF}
end.</syntaxhighlight>
 
test.pas:
 
<syntaxhighlight lang="pascal">program Test;
uses
ScriptedMain;
begin
write('Test: The meaning of life is: ');
writeln(MeaningOfLife())
end.</syntaxhighlight>
 
Example:
 
<syntaxhighlight lang="sh">$ make
$ ./scriptedmain
Main: The meaning of life is: 42
$ make test
$ ./test
Test: The meaning of life is: 42</syntaxhighlight>
 
=={{header|Perl}}==
Perl has scripted main. The code inside <tt>unless(caller) { ... }</tt> only runs when <tt>Life.pm</tt> is the main program.
 
<langsyntaxhighlight lang="perl">#!/usr/bin/env perl
 
# Life.pm
Line 986 ⟶ 1,409:
unless(caller) {
print "Main: The meaning of life is " . meaning_of_life() . "\n";
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="perl">#!/usr/bin/env perl
 
# death.pl
Line 997 ⟶ 1,420:
 
print "Life means " . Life::meaning_of_life . ".\n";
print "Death means invisible scary skeletons.\n";</langsyntaxhighlight>
=={{header|Perl 6}}==
Perl 6 automatically calls MAIN on direct invocation, but this may be a multi dispatch, so a library may have multiple "scripted mains".
<lang perl6>class LUE {
has $.answer = 42;
}
 
=={{header|Phix}}==
multi MAIN ('test') {
There is a builtin for this, which can even be asked to skip an arbitrary number of stack frames and that way find out exactly where it was effectively called from.
say "ok" if LUE.new.answer == 42;
<!--<syntaxhighlight lang="phix">(notonline)-->
}
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (includefile)</span>
 
<span style="color: #004080;">string</span> <span style="color: #000000;">mori</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">include_file</span><span style="color: #0000FF;">()=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">?</span><span style="color: #008000;">"main"</span><span style="color: #0000FF;">:</span><span style="color: #008000;">"an include"</span><span style="color: #0000FF;">)</span>
multi MAIN ('methods') {
<!--</syntaxhighlight>-->
say ~LUE.^methods;
}</lang>
 
=={{header|PHP}}==
Line 1,017 ⟶ 1,434:
scriptedmain.php
 
<langsyntaxhighlight lang="php"><?php
function meaning_of_life() {
return 42;
Line 1,029 ⟶ 1,446:
main($argv);
}
?></langsyntaxhighlight>
 
test.php
 
<langsyntaxhighlight lang="php"><?php
require_once("scriptedmain.php");
echo "Test: The meaning of life is " . meaning_of_life() . "\n";
?></langsyntaxhighlight>
 
=={{header|PicoLisp}}==
PicoLisp normally does it the other way round: It calls main from the command line with the '-' syntax if desired. Create an executable file (chmod +x) "life.l":
<langsyntaxhighlight PicoLisplang="picolisp">#!/usr/bin/picolisp /usr/lib/picolisp/lib.l
 
(de meaningOfLife ()
Line 1,047 ⟶ 1,464:
(de lifemain ()
(prinl "Main: The meaning of life is " (meaningOfLife))
(bye) )</langsyntaxhighlight>
and an executable file (chmod +x) "test.l":
<langsyntaxhighlight PicoLisplang="picolisp">#!/usr/bin/picolisp /usr/lib/picolisp/lib.l
 
(load "life.l")
 
(prinl "Test: The meaning of life is " (meaningOfLife))
(bye)</langsyntaxhighlight>
Test:
<pre>$ ./life.l -lifemain
Line 1,065 ⟶ 1,482:
Python has scripted main.
 
<langsyntaxhighlight lang="python">#!/usr/bin/env python
 
# life.py
Line 1,073 ⟶ 1,490:
 
if __name__ == "__main__":
print ("Main: The meaning of life is %s" % meaning_of_life())</langsyntaxhighlight>
 
<langsyntaxhighlight lang="python">#!/usr/bin/env python
 
# death.py
Line 1,081 ⟶ 1,498:
from life import meaning_of_life
 
print ("Life means %s." % meaning_of_life())
print ("Death means invisible scary skeletons.")</langsyntaxhighlight>
 
=={{header|SmalltalkR}}==
A way to check if code is running at "top level" is to check <code>length(sys.frames())</code>. This value will be zero for a file being run with <code>Rscript</code>, the <code>--file=</code> argument, or at the command line, and will be greater than 0 in all other conditions (such as package loading or code being sourced from another file.)
 
<syntaxhighlight lang="r">#!/usr/bin/env Rscript
Note that the ScriptedMain package must be installed in order for test.st to access code from scriptedmain.st.
 
meaningOfLife <- function() {
Example
42
}
 
main <- function(args) {
<lang shell>$ gst-package -t ~/.st package.xml &>/dev/null
cat("Main: The meaning of life is", meaningOfLife(), "\n")
}
 
if (length(sys.frames()) > 0) {
$ ./scriptedmain.st
args <- commandArgs(trailingOnly = FALSE)
Main: The meaning of life is 42
main(args)
q("no")
}</syntaxhighlight>
 
$ ./test.stR
Test: The meaning of life is 42</lang>
 
<syntaxhighlight lang="r">#!/usr/bin/env Rscript
package.xml
 
source("scriptedmain.R")
<lang xml><packages>
<package>
<name>ScriptedMain</name>
<filein>scriptedmain.st</filein>
<file>scriptedmain.st</file>
</package>
</packages></lang>
 
cat("Test: The meaning of life is", meaningOfLife(), "\n")
scriptedmain.st
 
q("no")</syntaxhighlight>
<lang smalltalk>"exec" "gst" "-f" "$0" "$0" "$@"
"exit"
 
=={{header|Racket}}==
Object subclass: ScriptedMain [
scriptedmain.rkt:
ScriptedMain class >> meaningOfLife [ ^42 ]
<syntaxhighlight lang="racket">#!/usr/bin/env racket
]
#lang racket
 
(provide meaning-of-life)
| main |
 
(define (meaning-of-life) 42)
main := [
Transcript show: 'Main: The meaning of life is ', ((ScriptedMain meaningOfLife) printString); cr.
].
 
(module+ main (printf "Main: The meaning of life is ~a\n" (meaning-of-life)))</syntaxhighlight>
(((Smalltalk getArgc) > 0) and: [ ((Smalltalk getArgv: 1) endsWith: 'scriptedmain.st') ]) ifTrue: [
main value.
].</lang>
 
test.strkt:
<syntaxhighlight lang="racket">#!/usr/bin/env racket
#lang racket
 
(module+ main
<lang smalltalk>"exec" "gst" "-f" "$0" "$0" "$@"
(require "scriptedmain.rkt")
"exit"
(printf "Test: The meaning of life is ~a\n" (meaning-of-life)))</syntaxhighlight>
 
=={{header|Raku}}==
"
(formerly Perl 6)
PackageLoader fileInPackage: 'ScriptedMain'.
Raku automatically calls MAIN on direct invocation, but this may be a multi dispatch, so a library may have multiple "scripted mains".
 
<syntaxhighlight lang="raku" line>class LUE {
Transcript show: 'Test: The meaning of life is ', ((ScriptedMain meaningOfLife) printString); cr.</lang>
has $.answer = 42;
 
=={{header|R}}==
R does not have scripted main, but the feature is easily added with regular expressions.
 
scriptedmain.R
 
<lang R>#!/usr/bin/Rscript
 
meaningOfLife <- function() {
42
}
 
multi MAIN ('test') {
main <- function(program, args) {
say "ok" if LUE.new.answer == 42;
cat("Main: The meaning of life is", meaningOfLife(), "\n")
}
 
multi MAIN ('methods') {
getProgram <- function(args) {
say ~LUE.^methods;
sub("--file=", "", args[grep("--file=", args)])
}</syntaxhighlight>
}
 
=={{header|REXX}}==
args <- commandArgs(trailingOnly = FALSE)
<syntaxhighlight lang="rexx">/*REXX program detects whether or not it is a "scripted main" program. */
program <- getProgram(args)
parse source . howInvoked @fn /*query REXX how this pgm got invoked. */
 
say 'This program ('@fn") was invoked as a: " howInvoked
if (length(program) > 0 && length(grep("scriptedmain", program)) > 0) {
main(program, args)
q("no")
}</lang>
 
if howInvoked\=='COMMAND' then do
test.R
say 'This program ('@fn") wasn't invoked via a command."
exit 12
end
 
/*╔════════════════════════════════════════════════════════════════════════════════╗
<lang R>#!/usr/bin/Rscript
║ At this point, we know that this program was invoked via the "command line" ║
║ or a program using the "command interface" and not via another program. ║
╚════════════════════════════════════════════════════════════════════════════════╝*/
 
/*────────────────────────────── The main code follows here ... ────────────────────────*/
source("scriptedmain.R")
say
say '(from' @fn"): and away we go ···"</syntaxhighlight> <br><br>
 
=={{header|Ring}}==
cat("Test: The meaning of life is", meaningOfLife(), "\n")
<syntaxhighlight lang="ring">
# Project : Modulinos
 
func meaningoflife()
q("no")</lang>
y = 42
return y
func main()
see "Main: The meaning of life is " + meaningoflife() + nl
</syntaxhighlight>
Output:
<pre>
Main: The meaning of life is 42
</pre>
 
=={{header|Ruby}}==
Ruby has scripted main.
 
<langsyntaxhighlight lang="ruby"># life.rb
 
def meaning_of_life
Line 1,185 ⟶ 1,611:
if __FILE__ == $0
puts "Main: The meaning of life is #{meaning_of_life}"
end</langsyntaxhighlight>
 
<langsyntaxhighlight lang="ruby"># death.rb
 
require 'life'
 
puts "Life means #{meaning_of_life}."
puts "Death means invisible scary skeletons."</langsyntaxhighlight>
 
=={{header|SACRust}}==
'''Note:''' this code is deprecated, and does not compile with Rust 1.0.0 and newer.
 
Makefile:
<langsyntaxhighlight lang="make">all: scriptedmain
 
scriptedmain: scriptedmain.rs
rustc scriptedmain.rs
 
test: test.rs scriptedmain.rs
rustc --lib scriptedmain.rs
rustc test.rs -L .
 
clean:
-rm test
-rm -rf *.dylib
-rm scriptedmain
-rm -rf *.dSYM</syntaxhighlight>
 
scriptedmain.rs:
<syntaxhighlight lang="rust">#[link(name = "scriptedmain")];
 
use std;
 
fn meaning_of_life() -> int {
ret 42;
}
 
fn main() {
std::io::println("Main: The meaning of life is " + core::int::to_str(meaning_of_life(), 10u));
}</syntaxhighlight>
 
test.rs:
<syntaxhighlight lang="rust">use scriptedmain;
use std;
 
fn main() {
std::io::println("Test: The meaning of life is " + core::int::to_str(scriptedmain::meaning_of_life(), 10u));
}</syntaxhighlight>
 
Example:
<syntaxhighlight lang="sh">$ make
$ make test
$ ./scriptedmain
Main: The meaning of life is 42
$ ./test
Test: The meaning of life is 42</syntaxhighlight>
 
=={{header|SAC}}==
Makefile:
<syntaxhighlight lang="make">all: scriptedmain
 
scriptedmain: ScriptedMain.sac
Line 1,213 ⟶ 1,686:
-rm libScriptedMainMod.a
-rm scriptedmain
-rm scriptedmain.c</langsyntaxhighlight>
 
ScriptedMain.sac:
<langsyntaxhighlight lang="c">#ifndef scriptedmain
module ScriptedMain;
#endif
Line 1,233 ⟶ 1,706:
return(0);
}
#endif</langsyntaxhighlight>
 
test.sac:
<langsyntaxhighlight lang="c">use StdIO: all;
use Array: all;
use ScriptedMain: all;
Line 1,243 ⟶ 1,716:
printf("Test: The meaning of life is %d\n", meaning_of_life());
return(0);
}</langsyntaxhighlight>
 
Example:
<langsyntaxhighlight lang="sh">$ make
$ make test
$ ./scriptedmain
Main: The meaning of life is 42
$ ./test
Test: The meaning of life is 42</langsyntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}
{{works with|Scala|2.10.2}}
 
===Unix shell script===
This code must be stored as a shell script.
<syntaxhighlight lang="bash">#!/bin/sh
exec scala "$0" "$@"
!#
def hailstone(n: Int): Stream[Int] =
n #:: (if (n == 1) Stream.empty else hailstone(if (n % 2 == 0) n / 2 else n * 3 + 1))
 
val nr = argv.headOption.map(_.toInt).getOrElse(27)
val collatz = hailstone(nr)
println(s"Use the routine to show that the hailstone sequence for the number: $nr.")
println(collatz.toList)
println(s"It has ${collatz.length} elements.")</syntaxhighlight>
 
===Windows Command Script===
This code must be stored as a Windows Command Script e.g. Hailstone.cmd
<syntaxhighlight lang="winbatch">::#!
@echo off
call scala %0 %*
pause
goto :eof
::!#
def hailstone(n: Int): Stream[Int] =
n #:: (if (n == 1) Stream.empty else hailstone(if (n % 2 == 0) n / 2 else n * 3 + 1))
 
val nr = argv.headOption.map(_.toInt).getOrElse(27)
val collatz = hailstone(nr)
println(s"Use the routine to show that the hailstone sequence for the number: $nr.")
println(collatz.toList)
println(s"It has ${collatz.length} elements.")
</syntaxhighlight>
{{out}}
<pre>C:\>Hailstone.cmd 42
Use the routine to show that the hailstone sequence for the number: 42.
List(42, 21, 64, 32, 16, 8, 4, 2, 1)
It has 9 elements.</pre>
 
=={{header|Scheme}}==
{{Works with|Chicken Scheme}}
Chicken Scheme has the {{{ -ss }}} flag for the interpreter, but compiled Chicken Scheme programs do not have scripted main unless the behavior is added manually to the code.
 
scriptedmain.scm
 
<syntaxhighlight lang="scheme">#!/bin/sh
#|
exec csi -ss $0 ${1+"$@"}
exit
|#
 
(use posix)
(require-extension srfi-1) ; lists
 
(define (meaning-of-life) 42)
 
(define (main args)
(display (format "Main: The meaning of life is ~a\n" (meaning-of-life)))
(exit))
 
(define (program)
(if (string=? (car (argv)) "csi")
(let ((s-index (list-index (lambda (x) (string-contains x "-s")) (argv))))
(if (number? s-index)
(cons 'interpreted (list-ref (argv) (+ 1 s-index)))
(cons 'unknown "")))
(cons 'compiled (car (argv)))))
 
(if (equal? (car (program)) 'compiled)
(main (cdr (argv))))</syntaxhighlight>
 
test.scm
 
<syntaxhighlight lang="scheme">#!/bin/sh
#|
exec csi -ss $0 ${1+"$@"}
exit
|#
(define (main args)
(load "scriptedmain.scm")
(display (format "Test: The meaning of life is ~a\n" (meaning-of-life)))
(exit))</syntaxhighlight>
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby"># Life.sm
 
func meaning_of_life {
42
}
 
if (__FILE__ == __MAIN__) {
say "Main: The meaning of life is #{meaning_of_life()}"
}</syntaxhighlight>
 
<syntaxhighlight lang="ruby"># test.sf
 
include Life
 
say "Test: The meaning of life is #{Life::meaning_of_life()}."</syntaxhighlight>
 
=={{header|Smalltalk}}==
 
Note that the ScriptedMain package must be installed in order for test.st to access code from scriptedmain.st.
 
Example
 
<syntaxhighlight lang="shell">$ gst-package -t ~/.st package.xml &>/dev/null
 
$ ./scriptedmain.st
Main: The meaning of life is 42
 
$ ./test.st
Test: The meaning of life is 42</syntaxhighlight>
 
package.xml
 
<syntaxhighlight lang="xml"><packages>
<package>
<name>ScriptedMain</name>
<filein>scriptedmain.st</filein>
<file>scriptedmain.st</file>
</package>
</packages></syntaxhighlight>
 
scriptedmain.st
 
<syntaxhighlight lang="smalltalk">"exec" "gst" "-f" "$0" "$0" "$@"
"exit"
 
Object subclass: ScriptedMain [
ScriptedMain class >> meaningOfLife [ ^42 ]
]
 
| main |
 
main := [
Transcript show: 'Main: The meaning of life is ', ((ScriptedMain meaningOfLife) printString); cr.
].
 
(((Smalltalk getArgc) > 0) and: [ ((Smalltalk getArgv: 1) endsWith: 'scriptedmain.st') ]) ifTrue: [
main value.
].</syntaxhighlight>
 
test.st
 
<syntaxhighlight lang="smalltalk">"exec" "gst" "-f" "$0" "$0" "$@"
"exit"
 
"
PackageLoader fileInPackage: 'ScriptedMain'.
 
Transcript show: 'Test: The meaning of life is ', ((ScriptedMain meaningOfLife) printString); cr.</syntaxhighlight>
 
=={{header|Swift}}==
 
Swift requires a number of hacks and boilerplate, but it is possible to write a modulino nevertheless.
 
Example
 
<syntaxhighlight lang="shell">$ make
mkdir -p bin/
swiftc -D SCRIPTEDMAIN -o bin/ScriptedMain ScriptedMain.swift
swiftc -emit-library -module-name ScriptedMain -emit-module ScriptedMain.swift
mkdir -p bin/
swiftc -D TEST -o bin/Test Test.swift -I "." -L "." -lScriptedMain -module-link-name ScriptedMain
bin/ScriptedMain
Main: The meaning of life is 42
bin/Test
Test: The meaning of life is 42</syntaxhighlight>
 
Makefile
 
<syntaxhighlight lang="make">all: bin/ScriptedMain bin/Test
bin/ScriptedMain
bin/Test
 
bin/ScriptedMain: ScriptedMain.swift
mkdir -p bin/
swiftc -D SCRIPTEDMAIN -o bin/ScriptedMain ScriptedMain.swift
 
ScriptedMain.swiftmodule: ScriptedMain.swift
swiftc -emit-library -module-name ScriptedMain -emit-module ScriptedMain.swift
 
bin/Test: Test.swift ScriptedMain.swiftmodule
mkdir -p bin/
swiftc -D TEST -o bin/Test Test.swift -I "." -L "." -lScriptedMain -module-link-name ScriptedMain
 
clean:
-rm -rf bin/
-rm *.swiftmodule
-rm *.swiftdoc
-rm *.dylib
</syntaxhighlight>
 
ScriptedMain.swift
 
<syntaxhighlight lang="swift">import Foundation
 
public class ScriptedMain {
public var meaningOfLife = 42
 
public init() {}
 
public class func main() {
var meaning = ScriptedMain().meaningOfLife
 
println("Main: The meaning of life is \(meaning)")
}
}
 
#if SCRIPTEDMAIN
@objc class ScriptedMainAutoload {
@objc class func load() {
ScriptedMain.main()
}
}
#endif
</syntaxhighlight>
 
Test.swift
 
<syntaxhighlight lang="swift">import Foundation
import ScriptedMain
 
public class Test {
public class func main() {
var meaning = ScriptedMain().meaningOfLife
 
println("Test: The meaning of life is \(meaning)")
}
}
 
#if TEST
@objc class TestAutoload {
@objc class func load() {
Test.main()
}
}
#endif
</syntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc main {args} {
puts "Directory: [pwd]"
puts "Program: $::argv0"
Line 1,263 ⟶ 1,979:
if {$::argv0 eq [info script]} {
main {*}$::argv
}</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
Line 1,270 ⟶ 1,986:
scriptedmain.sh
 
<langsyntaxhighlight lang="sh">#!/usr/bin/env sh
 
meaning_of_life() {
Line 1,284 ⟶ 2,000:
then
main
fi</langsyntaxhighlight>
 
test.sh
 
<syntaxhighlight lang ="sh">#!/usr/bin/env shbash
 
source scriptedmain.sh
path=$(dirname -- "$0")
source "$path/scriptedmain"
 
meaning_of_life
echo "Test: The meaning of life is $?"</lang>
</syntaxhighlight>
 
=={{header|Wren}}==
As far as Wren is concerned, a modulino and an executable library seem to be different names for the same thing. This therefore uses the same technique as the [[Executable_library#Wren]] task to create a simple modulino.
 
Note that Wren doesn't need or normally use a ''main()'' function to start a script, though we use one here to make the example clearer.
 
First we create a module for our modulino:
<syntaxhighlight lang="wren">/* Modulinos.wren */
 
var MeaningOfLife = Fn.new { 42 }
 
var main = Fn.new {
System.print("The meaning of life is %(MeaningOfLife.call()).")
}
 
// Check if it's being used as a library or not.
import "os" for Process
if (Process.allArguments[1] == "Modulinos.wren") { // if true, not a library
main.call()
}</syntaxhighlight>
 
and run it to make sure it works OK when run directly:
{{output}}
<pre>
The meaning of life is 42.
</pre>
 
Next we create another module which imports the modulino:
<syntaxhighlight lang="wren">/* Modulinos_main.wren */
 
import "./Modulinos" for MeaningOfLife
 
var main = Fn.new {
System.print("Who says the meaning of life is %(MeaningOfLife.call())?")
}
 
main.call()</syntaxhighlight>
 
and run this to make sure the modulino's ''main()'' function doesn't run:
{{output}}
<pre>
Who says the meaning of life is 42?
</pre>
 
=={{header|ZX Spectrum Basic}}==
Line 1,297 ⟶ 2,060:
On the ZX Spectrum, there is no main function as such, however a saved program can be made to start running from a particular line number by providing the line number as a parameter to save command. If the program is being merged as a module, then it does not run automatically. The following example will save the program in memory so that it starts running from line 500:
 
<langsyntaxhighlight lang="zxbasic">SAVE "MYPROG" LINE 500: REM For a program with main code starting at line 500</langsyntaxhighlight>
 
{{omit from|Ada}}
9,482

edits