I am setting a function (let’s say, A)that requires a library. I would like to put the function in a common file and call it with include from other files. To use such a function as any other Julia functions, the library should be updated only when the A is called, but if I put using inside A, I get the error
syntax: "using" expression not at top level
What would be the correct syntax to call a library inside a function?
Thank you
Well, you don’t call the library, you call a function from the library. Thus, put the using outside the function. If you want to “hide” the library from the global scope, put the using and the function inside a module and export the function:
module ContainsA
import Library
A(x) = 2*Library.f(x)
export A
end
Thank you, that is interesting. I tried with this:
module plotter
using PyPlot
function plotIt(y)
clf()
myPlot = plot(1:length(y), y, color = "blue", linestyle = "-")
ax = gca()
xlabel("X-axis")
ylabel("Y-axis")
Title = string("Vector of lenght ", length(y))
title(Title)
savefig("pyPlotted.png",
dpi = 300, format = "png", transparent = false)
end
end
I saved it in the file ~/plotter.jl. The function on its own works but when I call the file on a vector I prepared:
You want to call plotIt from outside the module plotter. That is why jling said that plotIt is at Main.plotter.plotIt. So, basically, you’ve loaded the module plotter into the Main REPL, and plotIt is inside that.
To call it, use
julia> include("~/plotter.jl")
Main.plotter
julia> using .plotter # Load local module.
julia> plotter.plotIt(upwards)
Or, if you add export plotIt below the line module plotter, then you can use