@track things. HOWTO: Is it possible to create global scope variable from local scope (function)

Hey Julianners,

I want something like this:

function fn(m) 
  # very compley function... and "m" would be a complex shit... that is hard to print
  @track modelsss m[1]=4+9 # mimicing a possible case
  # ex.: using m[1] later on 
end
c=[3,4]
fn(c)
modelsss

I have this @track macro:

macro track(var, ex)
	esc(quote
			((@isdefined $var) == false) && ($var = []); # create the variable... but it is only LOCAL scope :(
			res = $ex
			push!($var, res)
	end)
end

But this create a local variable.
Is this even possible? Or I have to have a evasion maneuver like creating the variable outside and calling global beforehand :frowning:

Bests!
Marcell

Wow I think I solved…

macro track(var, ex)
	esc(quote
			((@isdefined $var) == false) && (global $var = []);
			res = $ex
			push!($var, res)
	end)
end

I didn’t know if this is this easy… :o Julia constinously suprise me!

Anyway I hope it is a useful macro for everyone! :wink:

One more improvement, so we don’t run our expression’s return:

macro track(var, ex)
	esc(quote
			((@isdefined $var) == false) && (global $var = []);
			res = $ex
			push!($var, res)
			res
	end)
end

You’ll want to selectively escape var and ex rather than the whole block.

1 Like

What is the difference in the behind?

I lack too much knowledge to implement this on the macro field in spite I tried to understand a year before:

macro track(vari, ex)
	eva = esc(vari)
	eex = esc(ex)
	quote
		((@isdefined $eva) == false) && (global $eva = []);
		res = $eex
		push!($eva, res)
		res
	end
end

This is somehow terribly wrong. And errors everywhere… :smiley:
I used escaping too long time ago and just cannot remeber how to do it… :confused:

My video could be helpful here :slight_smile:

1 Like

I stuck with a "module scope variable @isdefined checkin sadly… :

macro track(vari, ex)
	eva = esc(vari)
	eex = esc(ex)
	quote
		esc(((@isdefined $((vari))) == false) && (global $vari = []));
		res = $eex
		push!($eva, res)
		res
	end
end

I don’t know how to check the “vari” in the “Main.” scope I think.

Ok, I think I do this and at least I make a little macro higiene:

macro track(var, ex)
	res = gensym()
	esc(quote
			((@isdefined $var) == false) && (global $var = []);
			$res = $ex
			push!($var, $res)
			$res
	end)
end