Init or main function in Julia
Asked Answered
S

2

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

Slayton answered 13/2, 2016 at 22:49 Comment(0)
H
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()
Hudspeth answered 14/2, 2016 at 1:58 Comment(2)
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.Hidalgo
#14463057 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.Hudspeth
S
0

The current beta release of Julia 1.11 exports Base.@main, which instructs Julia to run the marked function:

function (@main)(args)
   println("Hello, world!")
end

See https://docs.julialang.org/en/v1.11.0-rc2/manual/command-line-interface/#The-Main.main-entry-point

Splashy answered 22/8 at 13:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.