Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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


Now I work in notebook with the command:



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:

  g::usage =""   
  End[ ]    
EndPackage[ ]

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

share|improve this question
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. –  The Toad 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=Global`t" in package and it is still wrong. –  cmc Jul 13 '13 at 17:51
If you do g[x_] := x /. Global`t -> 3, it should work. –  The Toad 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 1

up vote 5 down vote accepted

For the specific example you provided, you can replace t with Global`t 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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.