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
Tomasz Wysocki
  • 11,170
  • 6
  • 47
  • 62
mcandre
  • 22,868
  • 20
  • 88
  • 147
  • 6
    Perhaps, ask what is *really* desired instead of showcasing how the *intended behavior* is obtained in other languages. –  Aug 05 '11 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 Aug 05 '11 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. – Rosh Oxymoron Aug 05 '11 at 19:09
  • The desired behavior is to do this from within the same module. – mcandre Aug 05 '11 at 20:06
  • i am really puzzled what is intent for this code? if you don't want to be called by someone else , you could always analyze the stack, checking any object(s) you desire and then make it or not, depending on outcome. I'm not sure, but i don't even think that there is such thing as __name__ or main or _this_file_. (at least in image-based smalltalk environment it doesn't makes any sense) – Igor Stasenko Aug 05 '11 at 21:15
  • Igor, I agree. Smalltalk's prerogative is to evaluate expressions inside a GUI window inside a VM. For Squeak and Pharo, it hardly seems possible to achieve the Python, etc. etc. behavior. Yet for GST, it's certainly possible if one can access the current code's filename. When code is not run inside a GUI but in Bash (e.g. `$ gst hash_lib.st`), it's very useful to include a command line interface while allowing other code (`$ gst md5.st`) to import the former's code without running its main function. – mcandre Aug 05 '11 at 21:44
  • 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 Aug 18 '11 at 16:02

1 Answers1

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.
].
mcandre
  • 22,868
  • 20
  • 88
  • 147