I have this module:
export test_func
function test_func()
return funk(x)
end
end
and I have this program
funk(x) = 2
test_func()
which gives the error UndefVarError: funk not defined
. Is there a way to make this work. I want to have a module I can load that might use the function defined in the program to which I have imported the module. Is it doable? I’ve tried setting global funk(x) = 2
but it seems to have no effect. Similarly it would be useful if the module functions could see constants declared in the main program.
Clarification: test_func is actually a macro so all its input is an expression,
You should just pass funk as an argument to func:
func(funk, 3)
Things are unfortunately more complicated, by example probably were to simplified.
the function I call is actually and macro so the input is just an expression. Ideally I would like the module function to see (a few limited) function declared in the scope which uses the module. But it could work if there was some way to initialise the module so that it had a few functions it could use.
Functions and macros are very different, and It’s not very clear what you want to do. Please provide a minimal working example.
It sounds like you may be able to get the desired result by suitable use of escaping within your macro though.
I had hoped to make the given example as minimal as possible, but you should be right that I could have given a better one.
This is my module:
module testMod
export @test_macro
macro test_macro(ex)
eval(:(f(x) = $ex))
return f
end
end
This is my program
using testMod
H(x) = 2x
f = @test_macro begin
2
end
println(f(2)
which gives UndefVarError: H not defined
however if I set
f = @test_macro begin
H(x)
end
I correctly get 2
.
I would also want to use
using testMod
const c = 3
f = @test_macro begin
3x
end
println(f(2)
Think of a macro as a syntax rewriter. You give it some syntax and it spits out new syntax. Here you are using eval
inside macro which is rarely correct.
I’m still confused what you want to do. Write the text you want to write inside the macro and the text you want to transform to.
1 Like
Works if you close bracket for print function in the last line.