# How can a package use a variable of a notebook?

I have defined a function g in a package. It is:

 g[x_]:=x/.t->3


Now I work in notebook with the command:

 a=t+1;

g[a]


The result is not 4 but 1+t. What can I do to get the result of 4?

The package file "pack1.m" is like this:

BeginPackage["pack1"]
g::usage =""
Begin["Private"]
g[x_]:=x/.t->3
End[ ]
EndPackage[ ]


And I use <<pack1.m to load it.

-
In which context have you defined your package functions? Have you made them "public"? Have you imported them to the current session? Are you sure you're using the same g? It should work if you've done it right. – R. M. Jul 13 '13 at 17:33
I don't know how to make a variable "public". I want to share "t" between two context. I add "t=Globalt" in package and it is still wrong. – cmc Jul 13 '13 at 17:51
If you do g[x_] := x /. Globalt -> 3, it should work. – R. M. Jul 13 '13 at 17:57
Now it work nice. Thank you. – cmc Jul 13 '13 at 18:01
Related question. – Leonid Shifrin Jul 14 '13 at 12:06

## 1 Answer

For the specific example you provided, you can replace t with Globalt and it should work.

However, it is generally not a good idea to access/share/set Global variables with a package. While it is OK for small cases like this, if you make this a habit, you'll run into troubles with larger packages, where it becomes harder to debug or if you share this package with someone else who doesn't know what transpires under the hood, or if you/they have accidentally set a value for t, etc.

Instead, I suggest using a slightly more verbose definition for g as (ignore the red coloring):

SetAttributes[g, HoldAll]
g[expr_, rule_, var_] := Block[{var}, expr /. rule]


which allows you more flexibility. You can now do g[t+1, t -> 3, t] to get 4, and it doesn't matter if you've already set a value for t in your current session. If you decide later to change the rule, you needn't edit your package... you simply need to change the second argument to g! You can tweak the above around to your specific needs, and perhaps infer the variable t automatically from rule`, etc., but the idea remains the same.

-