Using a julia module inside function

626 views
Skip to first unread message

El Afrit Mariem

unread,
Jul 9, 2014, 8:59:41 AM7/9/14
to julia...@googlegroups.com


Hi,

I was trying to use the Gaston module inside a function but I failed. I don't know if it's possible with Julia. If yes what is the correct syntax.

Thank you very much.

Steven G. Johnson

unread,
Jul 9, 2014, 11:13:55 AM7/9/14
to julia...@googlegroups.com
No, you are not allowed to have a "using" statement inside a function.

If you want to import a module but only use its symbols inside a specific function or set of functions, you have two options:

1) Use import:

import Foo
function bar(...)
    ... refer to Foo symbols via Foo.baz ...
end

    This loads the module Foo and defines a variable "Foo" that refers to the module, but does not import any of the other symbols from the module into the current namespace.  You refer to the Foo symbols by their qualified names Foo.bar etcetera.

2) Wrap your function in a module

module Bar
export bar
using Foo
function bar(...)
        ... refer to Foo.baz as simply baz ....
end 
end
using Bar

This imports all the symbols from Foo, but only inside the module Bar.

Tony Fong

unread,
Jul 10, 2014, 4:18:30 AM7/10/14
to julia...@googlegroups.com
Added to Lint.jl

Peter Simon

unread,
Jul 10, 2014, 9:01:03 AM7/10/14
to julia...@googlegroups.com
Added your useful answer to the FAQ in PR 7553

--Peter
Reply all
Reply to author
Forward
0 new messages