mcandre
mcandre

Reputation: 24642

Does Io have a equivalent to Python's if __name__=="__main__": main()?

It would be spiffy if Io had this, so that you could control whether code is run, e.g. a combination API-CLI coolstuff.io would run a command line interface, but only if run directly, not when coolstuff.io is imported by other Io code (which may have its own command line interface).

Upvotes: 2

Views: 80

Answers (1)

mcandre
mcandre

Reputation: 24642

ScriptedMain.io:

#!/usr/bin/env io

ScriptedMain := Object clone
ScriptedMain meaningOfLife := 42

main := method(
    "Main: The meaning of life is #{ScriptedMain meaningOfLife}" interpolate println
)

if (System args size > 0 and System args at(0) containsSeq("ScriptedMain"), main)

test.io:

#!/usr/bin/env io

main := method(
    "Test: The meaning of life is #{ScriptedMain meaningOfLife}" interpolate println
)

if (System args size > 0 and System args at(0) containsSeq("test"), main)

Example:

$ ./ScriptedMain.io 
Main: The meaning of life is 42
$ ./test.io
Test: The meaning of life is 42

Upvotes: 2

Related Questions