9

Does such a thing exist?

Ruby:

if __FILE__ == $0
    main
end

Perl:

unless(caller) {
    main;
}

Lua:

if type(package.loaded[(...)]) ~= "userdata" then
    main(arg)
else
    module(..., package.seeall)
end
7
  • 6
    Perhaps, ask what is really desired instead of showcasing how the intended behavior is obtained in other languages.
    – user166390
    Commented Aug 5, 2011 at 18:37
  • 1
    Desired: The syntax for a main function which is not run when this code is imported by other code. In other words, Python's if __name__=="__main__".
    – mcandre
    Commented Aug 5, 2011 at 18:52
  • 2
    Language-agnostic equivalent: Create another module/file that calls the main function from the other module/file, import the former and call the latter. Commented Aug 5, 2011 at 19:09
  • The desired behavior is to do this from within the same module.
    – mcandre
    Commented Aug 5, 2011 at 20:06
  • 3
    I think, mcandre want to know how to add code to library which will be only executed when library would be run separately (as oposite to included)
    – przemo_li
    Commented Aug 18, 2011 at 16:02

1 Answer 1

1

Exotic multiline shebangs and argv trickery do the job.

See Rosetta Code.

scriptedmain.st:

"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.
].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.