program-entry-pointjulia

Init or main function in Julia


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?)


Solution

  • 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()