Modulinos: Difference between revisions

Content added Content deleted
Line 1,363: Line 1,363:


=={{header|R}}==
=={{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.)
R does not have scripted main, but the feature is easily added with regular expressions.

scriptedmain.R


<lang R>#!/usr/bin/Rscript
<lang R>#!/usr/bin/Rscript
Line 1,373: Line 1,371:
}
}


main <- function(program, args) {
main <- function(args) {
cat("Main: The meaning of life is", meaningOfLife(), "\n")
cat("Main: The meaning of life is", meaningOfLife(), "\n")
}
}


if (length(sys.frames()) > 0) {
getProgram <- function(args) {
args <- commandArgs(trailingOnly = FALSE)
sub("--file=", "", args[grep("--file=", args)])
main(args)
}

args <- commandArgs(trailingOnly = FALSE)
program <- getProgram(args)

if (length(program) > 0 && length(grep("scriptedmain", program)) > 0) {
main(program, args)
q("no")
q("no")
}</lang>
}</lang>