Modulinos: Difference between revisions

Line 1,363:
 
=={{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
Line 1,373 ⟶ 1,371:
}
 
main <- function(program, args) {
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(program, args)
}
 
args <- commandArgs(trailingOnly = FALSE)
program <- getProgram(args)
 
if (length(program) > 0 && length(grep("scriptedmain", program)) > 0) {
main(program, args)
q("no")
}</lang>
Anonymous user