1.

Can I Use Using Or Import Inside A Function?

Answer»

No, you are not allowed to have a using or import 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:

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 etc.

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.

No, you are not allowed to have a using or import 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:

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 etc.

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.



Discussion

No Comment Found