Modulinos: Difference between revisions

6,962 bytes added ,  4 months ago
m
(Added AppleScript.)
m (→‎{{header|Wren}}: Minor tidy)
 
(12 intermediate revisions by 7 users not shown)
Line 5:
 
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:Modulinos]]''' for numerous attempts to understand the task and to rewrite the task description.''
Line 12 ⟶ 14:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">// life.11l
 
F meaning_of_life()
Line 18 ⟶ 20:
 
:start:
print(‘Main: The meaning of life is ’meaning_of_life())</langsyntaxhighlight>
 
<langsyntaxhighlight lang="11l">// death.11l
 
print(‘Life means ’life:meaning_of_life()‘.’)
print(‘Death means nothing.’)</langsyntaxhighlight>
 
=={{header|AppleScript}}==
Line 29 ⟶ 31:
AppleScript's equivalent of a main() function is a <tt>run</tt> handler, which can be either implicit or explicit:
 
<langsyntaxhighlight lang="applescript">display dialog "Hello"</langsyntaxhighlight>
or
<langsyntaxhighlight lang="applescript">on run
display dialog "Hello"
end run</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang="applescript">on run
if ((path to me) = (path to current application)) then
display dialog "I'm running in my own application."
Line 43 ⟶ 45:
display dialog "I'm being run from another script or application."
end if
end run</langsyntaxhighlight>
 
=={{header|Arturo}}==
Line 49 ⟶ 51:
===Library===
 
<langsyntaxhighlight lang="rebol">; modulinos - library
meaningOfLife: function [][
Line 56 ⟶ 58:
 
if standalone? ->
print ~"Library: The meaning of life is |meaningOfLife|"</langsyntaxhighlight>
 
{{out}}
Line 64 ⟶ 66:
===Main===
 
<langsyntaxhighlight lang="rebol">do.import relative "modulinos - library.art"
print ~"Life means |meaningOfLife|."
print "Death means invisible scary skeletons."</langsyntaxhighlight>
 
{{out}}
Line 82 ⟶ 84:
Example
 
<langsyntaxhighlight lang="sh">$ make
./scriptedmain
Main: The meaning of life is 42
./test
Test: The meaning of life is</langsyntaxhighlight>
 
Makefile
 
<langsyntaxhighlight lang="make">all: scriptedmain test
./scriptedmain
./test
Line 104 ⟶ 106:
-rm test
-rm scriptedmain.exe
-rm test.exe</langsyntaxhighlight>
 
scriptedmain.h
 
<syntaxhighlight lang ="c">int meaning_of_life();</langsyntaxhighlight>
 
scriptedmain.c
 
<langsyntaxhighlight lang="c">#include <stdio.h>
 
int meaning_of_life() {
Line 126 ⟶ 128:
}
 
#endif</langsyntaxhighlight>
 
test.c
 
<langsyntaxhighlight lang="c">#include "scriptedmain.h"
#include <stdio.h>
 
Line 138 ⟶ 140:
printf("Test: The meaning of life is %d\n", meaning_of_life());
return 0;
}</langsyntaxhighlight>
 
=={{header|C++}}==
Line 145 ⟶ 147:
Example
 
<langsyntaxhighlight lang="sh">$ make
./scriptedmain
Main: The meaning of life is 42
./test
Test: The meaning of life is 42</langsyntaxhighlight>
 
Makefile
 
<langsyntaxhighlight lang="make">all: scriptedmain test
./scriptedmain
./test
Line 167 ⟶ 169:
-rm test
-rm scriptedmain.exe
-rm test.exe</langsyntaxhighlight>
 
scriptedmain.h
 
<syntaxhighlight lang ="cpp">int meaning_of_life();</langsyntaxhighlight>
 
scriptedmain.cpp
 
<langsyntaxhighlight lang="cpp">#include <iostream>
 
using namespace std;
Line 190 ⟶ 192:
}
 
#endif</langsyntaxhighlight>
 
test.cpp
 
<langsyntaxhighlight lang="cpp">#include "scriptedmain.h"
#include <iostream>
 
Line 204 ⟶ 206:
cout << "Test: The meaning of life is " << meaning_of_life() << endl;
return 0;
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
Line 210 ⟶ 212:
 
scriptedmain.clj:
<langsyntaxhighlight lang="clojure">":";exec lein exec $0 ${1+"$@"}
":";exit
 
Line 222 ⟶ 224:
 
(when (.contains (first *command-line-args*) *source-path*)
(apply -main (rest *command-line-args*)))</langsyntaxhighlight>
 
test.clj:
<langsyntaxhighlight lang="clojure">":";exec lein exec $0 ${1+"$@"}
":";exit
 
Line 237 ⟶ 239:
 
(when (.contains (first *command-line-args*) *source-path*)
(apply -main (rest *command-line-args*)))</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
scriptedmain.coffee:
<langsyntaxhighlight lang="coffeescript">#!/usr/bin/env coffee
 
meaningOfLife = () -> 42
Line 250 ⟶ 252:
console.log "Main: The meaning of life is " + meaningOfLife()
 
if not module.parent then main()</langsyntaxhighlight>
 
test.coffee:
<langsyntaxhighlight lang="coffeescript">#!/usr/bin/env coffee
 
sm = require "./scriptedmain"
 
console.log "Test: The meaning of life is " + sm.meaningOfLife()</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
Line 266 ⟶ 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 305 ⟶ 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 316 ⟶ 318:
 
(load "scriptedmain.lisp")
(format t "Test: The meaning of life is ~a~%" (meaning-of-life))</langsyntaxhighlight>
 
=={{header|D}}==
Line 324 ⟶ 326:
scriptedmain.d:
 
<langsyntaxhighlight lang="d">#!/usr/bin/env rdmd -version=scriptedmain
 
module scriptedmain;
Line 338 ⟶ 340:
writeln("Main: The meaning of life is ", meaningOfLife());
}
}</langsyntaxhighlight>
 
test.d:
 
<langsyntaxhighlight lang="d">#!/usr/bin/env rdmd -version=test
 
import scriptedmain;
Line 351 ⟶ 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 364 ⟶ 366:
$ dmd test.d scriptedmain.d -version=test
$ ./test
Test: The meaning of life is 42</langsyntaxhighlight>
 
=={{header|Dart}}==
scriptedmain.dart:
<langsyntaxhighlight lang="dart">#!/usr/bin/env dart
 
#library("scriptedmain");
Line 378 ⟶ 380:
main() {
print("Main: The meaning of life is ${meaningOfLife()}");
}</langsyntaxhighlight>
 
test.dart:
<langsyntaxhighlight lang="dart">#!/usr/bin/env dart
 
#import("scriptedmain.dart", prefix: "scriptedmain");
Line 387 ⟶ 389:
main() {
print("Test: The meaning of life is ${scriptedmain.meaningOfLife()}");
}</langsyntaxhighlight>
 
Example:
<langsyntaxhighlight lang="sh">$ ./scriptedmain.dart
Main: The meaning of life is 42
$ ./test.dart
Test: The meaning of life is 42</langsyntaxhighlight>
 
=={{header|Emacs Lisp}}==
Line 400 ⟶ 402:
scriptedmain.el
 
<langsyntaxhighlight lang="lisp">:;exec emacs -batch -l $0 -f main $*
 
;;; Shebang from John Swaby
Line 408 ⟶ 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 420 ⟶ 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}}==
Line 426 ⟶ 463:
 
Makefile:
<langsyntaxhighlight lang="make">all: t
 
t: scriptedmain.beam test.beam
Line 439 ⟶ 476:
 
clean:
-rm *.beam</langsyntaxhighlight>
 
scriptedmain.erl:
<langsyntaxhighlight lang="erlang">-module(scriptedmain).
-export([meaning_of_life/0, start/0]).
 
Line 449 ⟶ 486:
start() ->
io:format("Main: The meaning of life is ~w~n", [meaning_of_life()]),
init:stop().</langsyntaxhighlight>
 
test.erl:
<langsyntaxhighlight lang="erlang">-module(test).
-export([start/0]).
-import(scriptedmain, [meaning_of_life/0]).
Line 458 ⟶ 495:
start() ->
io:format("Test: The meaning of life is ~w~n", [meaning_of_life()]),
init:stop().</langsyntaxhighlight>
 
=={{header|F Sharp|F#}}==
Line 472 ⟶ 509:
Example:
 
<langsyntaxhighlight lang="sh">$ make
fsharpc --out:scriptedmain.exe ScriptedMain.fs
fsharpc --out:test.exe ScriptedMain.fs Test.fs
Line 478 ⟶ 515:
Main: The meaning of life is 42
$ mono test.exe
Test: The meaning of life is 42</langsyntaxhighlight>
 
Makefile:
 
<langsyntaxhighlight lang="make">all: scriptedmain.exe test.exe
 
scriptedmain.exe: ScriptedMain.fs
Line 491 ⟶ 528:
 
clean:
-rm *.exe</langsyntaxhighlight>
 
ScriptedMain.fs:
 
<langsyntaxhighlight lang="fsharp">namespace ScriptedMain
 
module ScriptedMain =
Line 501 ⟶ 538:
 
let main =
printfn "Main: The meaning of life is %d" meaningOfLife</langsyntaxhighlight>
 
Test.fs:
 
<langsyntaxhighlight lang="fsharp">module Test =
open ScriptedMain
 
let main =
printfn "Test: The meaning of life is %d" ScriptedMain.meaningOfLife</langsyntaxhighlight>
 
=={{header|Factor}}==
Line 516 ⟶ 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 530 ⟶ 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 543 ⟶ 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 555 ⟶ 592:
: main ( -- ) meaning-of-life "Test: The meaning of life is " write number>string print ;
 
MAIN: main</langsyntaxhighlight>
 
=={{header|Forth}}==
Line 561 ⟶ 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 570 ⟶ 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 579 ⟶ 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 588 ⟶ 625:
{{works with|gforth}}
 
<langsyntaxhighlight lang="forth">#! /usr/bin/env forthscript
 
42 constant Douglas-Adams
Line 596 ⟶ 633:
[THEN]
 
cr .( Why aren't you running this as a script? It only provides a constant.)</langsyntaxhighlight>
 
 
=={{header|FreeBASIC}}==
{{trans|Ring}}
<syntaxhighlight lang="freebasic">
Function meaningoflife() As Byte
Dim As Byte y = 42
Return y
End Function
 
Sub main()
Print "Main: The meaning of life is "; meaningoflife()
End Sub
 
main()
Sleep
</syntaxhighlight>
{{out}}
<pre>
Main: The meaning of life is 42
</pre>
 
 
=={{header|Go}}==
Line 604 ⟶ 663:
 
First create these two files in the 'modulino' directory:
<langsyntaxhighlight lang="go">// modulino.go
package main
 
Line 615 ⟶ 674:
func libMain() {
fmt.Println("The meaning of life is", MeaningOfLife())
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="go">// modulino_main.go
package main
func main() {
libMain()
}</langsyntaxhighlight>
 
To emulate a modulino:
Line 633 ⟶ 692:
 
Now create this file in the 'mol' directory:
<langsyntaxhighlight lang="go">// mol.go
package main
 
Line 640 ⟶ 699:
func main() {
fmt.Println("The meaning of life is still", MeaningOfLife())
}</langsyntaxhighlight>
and copy modulino.go to the 'mol' directory. The library can then be used in the 'normal' way:
{{out}}
Line 653 ⟶ 712:
Example:
 
<langsyntaxhighlight lang="sh">$ ./ScriptedMain.groovy
Main: The meaning of life is 42
$ ./Test.groovy
Test: The meaning of life is 42</langsyntaxhighlight>
 
ScriptedMain.groovy:
 
<langsyntaxhighlight lang="groovy">#!/usr/bin/env groovy
 
class ScriptedMain {
Line 668 ⟶ 727:
println "Main: The meaning of life is " + meaningOfLife
}
}</langsyntaxhighlight>
 
Test.groovy:
 
<langsyntaxhighlight lang="groovy">#!/usr/bin/env groovy
 
println "Test: The meaning of life is " + ScriptedMain.meaningOfLife</langsyntaxhighlight>
 
=={{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 688 ⟶ 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 704 ⟶ 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 719 ⟶ 778:
 
main :: IO ()
main = putStrLn $ "Test: The meaning of life is " ++ show meaningOfLife</langsyntaxhighlight>
 
=={{header|Io}}==
Line 725 ⟶ 784:
ScriptedMain.io:
 
<langsyntaxhighlight lang="io">#!/usr/bin/env io
 
ScriptedMain := Object clone
Line 732 ⟶ 791:
if( isLaunchScript,
"Main: The meaning of life is #{ScriptedMain meaningOfLife}" interpolate println
)</langsyntaxhighlight>
 
test.io:
 
<langsyntaxhighlight lang="io">#!/usr/bin/env io
 
"Test: The meaning of life is #{ScriptedMain meaningOfLife}" interpolate println</langsyntaxhighlight>
 
<langsyntaxhighlight lang="sh">$ ./ScriptedMain.io
Main: The meaning of life is 42
$ ./test.io
Test: The meaning of life is 42</langsyntaxhighlight>
 
=={{header|J}}==
Line 749 ⟶ 808:
modulinos.ijs:
 
<langsyntaxhighlight lang="j">#!/usr/bin/env ijconsole
meaningOfLife =: 42
Line 764 ⟶ 823:
)
shouldrun 0</langsyntaxhighlight>
 
test.j:
 
<langsyntaxhighlight lang="j">#!/usr/bin/env jconsole
 
load 'modulinos.ijs'
Line 774 ⟶ 833:
echo 'Test: The meaning of life is ',": meaningOfLife
 
exit ''</langsyntaxhighlight>
 
Example:
 
<langsyntaxhighlight lang="sh">$ ./modulinos.ijs
Main: The meaning of life is 42
$ ./test.j
Test: The meaning of life is 42</langsyntaxhighlight>
 
=={{header|Java}}==
Line 788 ⟶ 847:
ScriptedMain.java
 
<langsyntaxhighlight lang="java">public class ScriptedMain {
public static int meaningOfLife() {
return 42;
Line 796 ⟶ 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}}==
Line 811 ⟶ 870:
 
scriptedmain.js
<langsyntaxhighlight lang="javascript">#!/usr/bin/env node
 
function meaningOfLife() { return 42; }
Line 821 ⟶ 880:
}
 
if (!module.parent) { main(); }</langsyntaxhighlight>
 
test.js
<langsyntaxhighlight lang="javascript">#!/usr/bin/env node
 
var sm = require("./scriptedmain");
 
console.log("Test: The meaning of life is " + sm.meaningOfLife());</langsyntaxhighlight>
 
=={{header|Julia}}==
Line 834 ⟶ 893:
<br />
In module file Divisors.jl:
<langsyntaxhighlight lang="julia">module Divisors
 
using Primes
Line 875 ⟶ 934:
Divisors.interactiveDivisors()
end
</syntaxhighlight>
</lang>
In a user file getdivisors.jl:
<langsyntaxhighlight lang="julia">include("divisors.jl")
 
using .Divisors
Line 883 ⟶ 942:
n = 708245926330
println("The proper divisors of $n are ", properdivisors(n))
</syntaxhighlight>
</lang>
 
=={{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 898 ⟶ 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 923 ⟶ 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 941 ⟶ 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 957 ⟶ 1,016:
 
ret i32 0
}</langsyntaxhighlight>
 
=={{header|Lua}}==
Line 964 ⟶ 1,023:
scriptedmain.lua
 
<langsyntaxhighlight lang="lua">#!/usr/bin/env lua
 
function meaningoflife()
Line 978 ⟶ 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|Make}}==
 
Example
<langsyntaxhighlight lang="sh">$ make -f scriptedmain.mf
The meaning of life is 42
(Main)
$ make -f test.mf
The meaning of life is 42
(Test)</langsyntaxhighlight>
 
scriptedmain.mf
<langsyntaxhighlight lang="make">all: scriptedmain
 
meaning-of-life:
Line 1,004 ⟶ 1,063:
scriptedmain: meaning-of-life
@echo "(Main)"
</syntaxhighlight>
</lang>
 
test.mf
<langsyntaxhighlight lang="make">all: test
 
test:
@make -f scriptedmain.mf meaning-of-life
@echo "(Test)"
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
 
scriptedmain.ma
<langsyntaxhighlight lang="mathematica">#!/usr/bin/env MathKernel -script
 
MeaningOfLife[] = 42
Line 1,032 ⟶ 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.
Line 1,051 ⟶ 1,110:
=={{header|Mozart/Oz}}==
Makefile:
<langsyntaxhighlight lang="make">all: run
 
run: scriptedmain test
Line 1,071 ⟶ 1,130:
-rm *.ozf
-rm *.exe
</syntaxhighlight>
</lang>
 
scriptedmain.oz:
<langsyntaxhighlight lang="oz">functor
export
meaningOfLife: MeaningOfLife
Line 1,092 ⟶ 1,151:
end
end
</syntaxhighlight>
</lang>
 
test.oz:
<langsyntaxhighlight lang="oz">functor
import
ScriptedMain
Line 1,109 ⟶ 1,168:
end
end
end</langsyntaxhighlight>
 
=={{header|newLISP}}==
Line 1,116 ⟶ 1,175:
scriptedmain.lsp
 
<langsyntaxhighlight lang="lisp">#!/usr/bin/env newlisp
 
(context 'SM)
Line 1,128 ⟶ 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|Nim}}==
Nim provides the predicate <code>isMainModule</code> to use with conditional compilation. Here is an example:
 
<syntaxhighlight lang="Nim">proc p*() =
## Some exported procedure.
echo "Executing procedure"
 
# Some code to execute to initialize the module.
echo "Initializing the module"
 
when isMainModule:
# Some code to execute if the module is run directly, for instance code to test the module.
echo "Running tests"
</syntaxhighlight>
 
{{out}}
When run directly, the result of execution is:
<pre>Initializing the module
Running tests
</pre>
If we call “p” from another module, we get:
<pre>Initializing the module
Executing procedure
</pre>
 
=={{header|Objective-C}}==
Line 1,142 ⟶ 1,226:
scriptedmain.h:
 
<langsyntaxhighlight lang="objc">#import <objc/Object.h>
 
@interface ScriptedMain: Object {}
Line 1,148 ⟶ 1,232:
+ (int)meaningOfLife;
 
@end</langsyntaxhighlight>
 
scriptedmain.m:
 
<langsyntaxhighlight lang="objc">#import "scriptedmain.h"
#import <Foundation/Foundation.h>
 
Line 1,171 ⟶ 1,255:
 
return 0;
}</langsyntaxhighlight>
 
test.m:
 
<langsyntaxhighlight lang="objc">#import "scriptedmain.h"
#import <Foundation/Foundation.h>
 
Line 1,186 ⟶ 1,270:
 
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 1,199 ⟶ 1,283:
scriptedmain.ml
 
<langsyntaxhighlight lang="ocaml">let meaning_of_life = 42
 
let main () =
Line 1,207 ⟶ 1,291:
let () =
if not !Sys.interactive then
main ()</langsyntaxhighlight>
 
Invoked as a script:
 
<langsyntaxhighlight lang="sh">$ ocaml scriptedmain.ml
Main: The meaning of life is 42</langsyntaxhighlight>
 
Loaded into an ocaml toplevel/utop:
 
<syntaxhighlight lang="text">$ ocaml
...
# #use "scriptedmain.ml";;
Line 1,223 ⟶ 1,307:
# meaning_of_life;;
- : int = 42
# </langsyntaxhighlight>
 
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.
Line 1,232 ⟶ 1,316:
meaningoflife.m
 
<langsyntaxhighlight lang="matlab">#!/usr/bin/env octave -qf
 
function y = meaningoflife()
Line 1,242 ⟶ 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}}==
Line 1,254 ⟶ 1,338:
Makefile:
 
<langsyntaxhighlight lang="make">all: scriptedmain
 
scriptedmain: scriptedmain.pas
Line 1,266 ⟶ 1,350:
-rm scriptedmain
-rm *.o
-rm *.ppu</langsyntaxhighlight>
 
scriptedmain.pas:
 
<langsyntaxhighlight lang="pascal">{$IFDEF scriptedmain}
program ScriptedMain;
{$ELSE}
Line 1,287 ⟶ 1,371:
writeln(MeaningOfLife())
{$ENDIF}
end.</langsyntaxhighlight>
 
test.pas:
 
<langsyntaxhighlight lang="pascal">program Test;
uses
ScriptedMain;
Line 1,297 ⟶ 1,381:
write('Test: The meaning of life is: ');
writeln(MeaningOfLife())
end.</langsyntaxhighlight>
 
Example:
 
<langsyntaxhighlight lang="sh">$ make
$ ./scriptedmain
Main: The meaning of life is: 42
$ make test
$ ./test
Test: The meaning of life is: 42</langsyntaxhighlight>
 
=={{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 1,325 ⟶ 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 1,336 ⟶ 1,420:
 
print "Life means " . Life::meaning_of_life . ".\n";
print "Death means invisible scary skeletons.\n";</langsyntaxhighlight>
 
=={{header|Phix}}==
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.
<!--<syntaxhighlight lang="phix">(notonline)-->
<lang Phix>string mori = iff(include_file()=1?"main":"an include")</lang>
<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>
<!--</syntaxhighlight>-->
 
=={{header|PHP}}==
Line 1,347 ⟶ 1,434:
scriptedmain.php
 
<langsyntaxhighlight lang="php"><?php
function meaning_of_life() {
return 42;
Line 1,359 ⟶ 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,377 ⟶ 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,395 ⟶ 1,482:
Python has scripted main.
 
<langsyntaxhighlight lang="python">#!/usr/bin/env python
 
# life.py
Line 1,403 ⟶ 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,412 ⟶ 1,499:
 
print("Life means %s." % meaning_of_life())
print("Death means invisible scary skeletons.")</langsyntaxhighlight>
 
=={{header|R}}==
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.)
 
<langsyntaxhighlight Rlang="r">#!/usr/bin/env Rscript
 
meaningOfLife <- function() {
Line 1,431 ⟶ 1,518:
main(args)
q("no")
}</langsyntaxhighlight>
 
test.R
 
<langsyntaxhighlight Rlang="r">#!/usr/bin/env Rscript
 
source("scriptedmain.R")
Line 1,441 ⟶ 1,528:
cat("Test: The meaning of life is", meaningOfLife(), "\n")
 
q("no")</langsyntaxhighlight>
 
=={{header|Racket}}==
scriptedmain.rkt:
<langsyntaxhighlight lang="racket">#!/usr/bin/env racket
#lang racket
 
Line 1,452 ⟶ 1,539:
(define (meaning-of-life) 42)
 
(module+ main (printf "Main: The meaning of life is ~a\n" (meaning-of-life)))</langsyntaxhighlight>
 
test.rkt:
<langsyntaxhighlight lang="racket">#!/usr/bin/env racket
#lang racket
 
(module+ main
(require "scriptedmain.rkt")
(printf "Test: The meaning of life is ~a\n" (meaning-of-life)))</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
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" perl6line>class LUE {
has $.answer = 42;
}
Line 1,475 ⟶ 1,562:
multi MAIN ('methods') {
say ~LUE.^methods;
}</langsyntaxhighlight>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program detects whether or not it is a "scripted main" program. */
parse source . howInvoked @fn /*query REXX how this pgm got invoked. */
 
Line 1,495 ⟶ 1,582:
/*────────────────────────────── The main code follows here ... ────────────────────────*/
say
say '(from' @fn"): and away we go ···"</langsyntaxhighlight> <br><br>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Modulinos
 
Line 1,507 ⟶ 1,594:
func main()
see "Main: The meaning of life is " + meaningoflife() + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,516 ⟶ 1,603:
Ruby has scripted main.
 
<langsyntaxhighlight lang="ruby"># life.rb
 
def meaning_of_life
Line 1,524 ⟶ 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|Rust}}==
Line 1,537 ⟶ 1,624:
 
Makefile:
<langsyntaxhighlight lang="make">all: scriptedmain
 
scriptedmain: scriptedmain.rs
Line 1,550 ⟶ 1,637:
-rm -rf *.dylib
-rm scriptedmain
-rm -rf *.dSYM</langsyntaxhighlight>
 
scriptedmain.rs:
<langsyntaxhighlight lang="rust">#[link(name = "scriptedmain")];
 
use std;
Line 1,563 ⟶ 1,650:
fn main() {
std::io::println("Main: The meaning of life is " + core::int::to_str(meaning_of_life(), 10u));
}</langsyntaxhighlight>
 
test.rs:
<langsyntaxhighlight 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));
}</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|SAC}}==
Makefile:
<langsyntaxhighlight lang="make">all: scriptedmain
 
scriptedmain: ScriptedMain.sac
Line 1,599 ⟶ 1,686:
-rm libScriptedMainMod.a
-rm scriptedmain
-rm scriptedmain.c</langsyntaxhighlight>
 
ScriptedMain.sac:
<langsyntaxhighlight lang="c">#ifndef scriptedmain
module ScriptedMain;
#endif
Line 1,619 ⟶ 1,706:
return(0);
}
#endif</langsyntaxhighlight>
 
test.sac:
<langsyntaxhighlight lang="c">use StdIO: all;
use Array: all;
use ScriptedMain: all;
Line 1,629 ⟶ 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}}==
Line 1,645 ⟶ 1,732:
===Unix shell script===
This code must be stored as a shell script.
<langsyntaxhighlight lang="bash">#!/bin/sh
exec scala "$0" "$@"
!#
Line 1,655 ⟶ 1,742:
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.")</langsyntaxhighlight>
 
===Windows Command Script===
This code must be stored as a Windows Command Script e.g. Hailstone.cmd
<langsyntaxhighlight lang="winbatch">::#!
@echo off
call scala %0 %*
Line 1,673 ⟶ 1,760:
println(collatz.toList)
println(s"It has ${collatz.length} elements.")
</syntaxhighlight>
</lang>
{{out}}
<pre>C:\>Hailstone.cmd 42
Line 1,686 ⟶ 1,773:
scriptedmain.scm
 
<langsyntaxhighlight lang="scheme">#!/bin/sh
#|
exec csi -ss $0 ${1+"$@"}
Line 1,710 ⟶ 1,797:
 
(if (equal? (car (program)) 'compiled)
(main (cdr (argv))))</langsyntaxhighlight>
 
test.scm
 
<langsyntaxhighlight lang="scheme">#!/bin/sh
#|
exec csi -ss $0 ${1+"$@"}
Line 1,722 ⟶ 1,809:
(load "scriptedmain.scm")
(display (format "Test: The meaning of life is ~a\n" (meaning-of-life)))
(exit))</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby"># Life.sm
 
func meaning_of_life {
Line 1,733 ⟶ 1,820:
if (__FILE__ == __MAIN__) {
say "Main: The meaning of life is #{meaning_of_life()}"
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="ruby"># test.sf
 
include Life
 
say "Test: The meaning of life is #{Life::meaning_of_life()}."</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
Line 1,747 ⟶ 1,834:
Example
 
<langsyntaxhighlight lang="shell">$ gst-package -t ~/.st package.xml &>/dev/null
 
$ ./scriptedmain.st
Line 1,753 ⟶ 1,840:
 
$ ./test.st
Test: The meaning of life is 42</langsyntaxhighlight>
 
package.xml
 
<langsyntaxhighlight lang="xml"><packages>
<package>
<name>ScriptedMain</name>
Line 1,763 ⟶ 1,850:
<file>scriptedmain.st</file>
</package>
</packages></langsyntaxhighlight>
 
scriptedmain.st
 
<langsyntaxhighlight lang="smalltalk">"exec" "gst" "-f" "$0" "$0" "$@"
"exit"
 
Line 1,782 ⟶ 1,869:
(((Smalltalk getArgc) > 0) and: [ ((Smalltalk getArgv: 1) endsWith: 'scriptedmain.st') ]) ifTrue: [
main value.
].</langsyntaxhighlight>
 
test.st
 
<langsyntaxhighlight lang="smalltalk">"exec" "gst" "-f" "$0" "$0" "$@"
"exit"
 
Line 1,792 ⟶ 1,879:
PackageLoader fileInPackage: 'ScriptedMain'.
 
Transcript show: 'Test: The meaning of life is ', ((ScriptedMain meaningOfLife) printString); cr.</langsyntaxhighlight>
 
=={{header|Swift}}==
Line 1,800 ⟶ 1,887:
Example
 
<langsyntaxhighlight lang="shell">$ make
mkdir -p bin/
swiftc -D SCRIPTEDMAIN -o bin/ScriptedMain ScriptedMain.swift
Line 1,809 ⟶ 1,896:
Main: The meaning of life is 42
bin/Test
Test: The meaning of life is 42</langsyntaxhighlight>
 
Makefile
 
<langsyntaxhighlight lang="make">all: bin/ScriptedMain bin/Test
bin/ScriptedMain
bin/Test
Line 1,833 ⟶ 1,920:
-rm *.swiftdoc
-rm *.dylib
</syntaxhighlight>
</lang>
 
ScriptedMain.swift
 
<langsyntaxhighlight lang="swift">import Foundation
 
public class ScriptedMain {
Line 1,858 ⟶ 1,945:
}
#endif
</syntaxhighlight>
</lang>
 
Test.swift
 
<langsyntaxhighlight lang="swift">import Foundation
import ScriptedMain
 
Line 1,880 ⟶ 1,967:
}
#endif
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc main {args} {
puts "Directory: [pwd]"
puts "Program: $::argv0"
Line 1,892 ⟶ 1,979:
if {$::argv0 eq [info script]} {
main {*}$::argv
}</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
Line 1,899 ⟶ 1,986:
scriptedmain.sh
 
<langsyntaxhighlight lang="sh">#!/usr/bin/env sh
 
meaning_of_life() {
Line 1,913 ⟶ 2,000:
then
main
fi</langsyntaxhighlight>
 
test.sh
 
<langsyntaxhighlight lang="sh">#!/bin/bash
 
path=$(dirname -- "$0")
Line 1,924 ⟶ 2,011:
meaning_of_life
echo "Test: The meaning of life is $?"
</syntaxhighlight>
</lang>
 
=={{header|Wren}}==
Line 1,932 ⟶ 2,019:
 
First we create a module for our modulino:
<langsyntaxhighlight ecmascriptlang="wren">/* modulinoModulinos.wren */
 
var MeaningOfLife = Fn.new { 42 }
Line 1,942 ⟶ 2,029:
// Check if it's being used as a library or not.
import "os" for Process
if (Process.allArguments[1] == "modulinoModulinos.wren") { // if true, not a library
main.call()
}</langsyntaxhighlight>
 
and run it to make sure it works OK when run directly:
Line 1,953 ⟶ 2,040:
 
Next we create another module which imports the modulino:
<langsyntaxhighlight ecmascriptlang="wren">/* modulino_mainModulinos_main.wren */
 
import "./modulinoModulinos" for MeaningOfLife
 
var main = Fn.new {
Line 1,961 ⟶ 2,048:
}
 
main.call()</langsyntaxhighlight>
 
and run this to make sure the modulino's ''main()'' function doesn't run:
Line 1,973 ⟶ 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,476

edits