13

I've read that global variables have a sensible impact on performance.

In order to avoid them I've put everything inside a init function, as I read here.

Simple example, integer.jl:

function __init__()
    n = 0
    while n < 2
        try
            print("Insert an integer bigger than 1: ")
            n = parse(Int8,readline(STDIN))
        catch Error
            println("Error!")
        end
    end

    println(n)
end

When I run julia integer.jl from the command line, nothing happens. function main() doesn't work either.

What should I do to make it work?

(Also, can you correct any errors, non efficient code or non idiomatic syntax?)

Community
  • 1
  • 1
Pigna
  • 2,792
  • 5
  • 29
  • 51

1 Answers1

24

The name __init__ is reserved as a name for a function in a module that is automatically run when the module is loaded, so unless that's what you're defining, don't use that name. You can call this function main (which has no special meaning) and then just call it like so:

function main()
    # do stuff
end

main()
StefanKarpinski
  • 32,404
  • 10
  • 86
  • 111
  • 4
    Does Julia have any guard like `if __name__ == '__main__':` in Python? This is sometimes useful for libraries that also have some kind of standalone debug/testing mode. – mojomex Jul 05 '20 at 13:14
  • 2
    https://stackoverflow.com/questions/14462557/within-a-julia-script-can-you-tell-whether-the-script-has-been-imported-or-exec but in short, I'm not sure why you'd need to be able to run the same file as a script or as something that defines a module. – StefanKarpinski Jul 06 '20 at 15:44