Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List all global variables

As noted elsewhere, you can list all user-defined symbols with this:

Names["Global`*"]

But I'd like to find just my global variables (I'm in the middle of some hairy debugging), not my function definitions. Something like this is close:

Select[Names["Global`*"], Head@Symbol[#]=!=Symbol && Head@Symbol[#]=!=Function&]

But that misses variables whose value is a symbol (perhaps I have x = Pi).

I could probably beat that thing into submission but maybe there's a cleaner, more direct way?

like image 914
dreeves Avatar asked Jul 18 '11 00:07

dreeves


People also ask

How do I see all global variables?

Once setup, open jslinter and go to Options->check everything on the left column except "tolerate unused parameters". Then run jslinter on the webpage and scroll down in the results. You will have a list of unused variables (global and then local to each function).

How many types of global variables are there?

There are three different ways to classify global variables: by the ownership of the variable, by the scope of the value, and by the method used to maintain the value.

Which are global variables?

A global variable is a variable that is declared in the global scope in other words, a variable that is visible from all other scopes. In JavaScript it is a property of the global object.

What are global variables in C?

Global variables are defined outside a function, usually on top of the program. Global variables hold their values throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program. A global variable can be accessed by any function.


1 Answers

If we consider any symbol with an own-value as a "variable", then this will do the trick:

ClearAll[variableQ]
variableQ[name_String] := {} =!= ToExpression[name, InputForm, OwnValues]

Select[Names["Global`*"], variableQ]

Note that this technique will fail on read-protected symbols and will misidentify some forms of auto-loaded functions.

Edit 1

As @Szabolcs points out, the definition of variableQ can be simplified if ValueQ is used:

variableQ[name_String] := ToExpression[name, InputForm, ValueQ]

Edit 2

As @dreeves points out, it might be desirable to filter out apparent variables whose values are functions, e.g. f = (#+1)&:

variableQ[name_String] :=
  MatchQ[
    ToExpression[name, InputForm, OwnValues]
  , Except[{} | {_ :> (Function|CompiledFunction)[___]}]
  ]

This definition could be easily extended to check for other function-like forms such as interpolating functions, auto-loaded symbols, etc.

like image 199
WReach Avatar answered Nov 16 '22 23:11

WReach