Search code examples
smalltalkprogram-entry-pointgnu-smalltalk

Python's if __name__=="__main__" idiom for GNU Smalltalk?


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

Solution

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