Test existence of global variable within function?

조회 수: 67 (최근 30일)
Romn
Romn 2018년 9월 12일
댓글: Stephen23 2024년 1월 26일
Hi, I want to access the status of a variable every where within different function. I created the global variable:
global debugFlag
debugFlag = true;
I create a function idebugging the goal will be to use them when developping other function as:
function output = myawesomefunction(input)
...
doing stuff
...
if isdebugging
fprintf(stuff)
end
...
end
The function I created is this one:
function existing = isdebugging()
%%Check if debugFlag global variable exist and is true
if exist('debugFlag', 'var')
existing = debugFlag;
else
existing = false;
end
end
But this function always return false.
I checked the answer to this question and tried with
W = evalin('caller','whos');
existing = ismember('debugFlag',[W(:).name])
But this always return true. How can I achieve the function I want? I am sure other people are achieving this for debugging, what is the proper method to have some debugging information?
Thank you.
  댓글 수: 1
Gabor
Gabor 2024년 1월 26일
Before going into all this nonsense:
ismember('variable_of_interest', who('global'))
credit to:Walter Roberson

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2018년 9월 12일
편집: Stephen23 2018년 9월 12일
You need to also explicitly declare that global variable inside the functions where you want to use it:
function existing = isdebugging()
global debugFlag % <- your need this!
existing = ~isempty(debugFlag) && debugFlag;
end
Note that there is absolutely no point in testing for the existence of that global variable because, as the global documentation clearly describes, "If the global variable does not exist the first time you issue the global statement, it is initialized to an empty 0x0 matrix." So it will always exist, but it can be empty, true, or false, depending on the state of your code. So those are the variable states that you need to check for in your function.
Personally I would recommend that you avoid using a global variable for this: given that you are happy to have a special function isdebugging, then you could easily use a persistent variable, which neatly encapsulates the functionality into one function and prevent unexpected interference with the global variable:
function otp = isdebugging(inp)
persistent state
state = (~isempty(state) && state) || (nargin>0 && inp);
otp = state;
end
Simply call it to set the state, e.g. isdebugging(true).
"I am sure other people are achieving this for debugging, what is the proper method to have some debugging information?"
Most experienced programmers use the inbuilt debugging tools:
  댓글 수: 3
Gabor
Gabor 2021년 2월 2일
I guess my workaround will be that I create it anyway and check it if it empty and if it is than I delete it right away.
Stephen23
Stephen23 2024년 1월 26일
편집: Stephen23 2024년 1월 26일
"Basically it is almost dangerouse to use global variable just because the fact it will start deleting variables if it is not declared where it suppose to."
It is certainly "dangerous" to use global variables. They are best avoided.
"Or I just miss the logic... why do we have to define it twice?"
You don't need to define global variables twice. However if you keep redefining it (including via the default value of a GLOBAL call if the variable does not exist in the global workspace) then it will have whatever value you gave it last. That the the whole point of global variables.
Of course you do need to declare it in every workspace where you want to refer to it:
funOne()
funTwo()
3.1416
funThree()
Warning: The value of local variables may have been changed to match the globals. Future versions of MATLAB will require that you declare a variable to be global before you use that variable.
funFour()
3.1416
function funOne()
global someval % this redefines the variable!
someval = pi;
end
function funTwo()
global someval
disp(someval)
end
function funThree()
someval = sqrt(2);
global someval
end
function funFour()
global someval
disp(someval)
end
The warning is there for a reason.
I agree that TMW should forbid usage before the variable is declared. That would resolve your accidental creating of empty variables (as would defining them as global at the top of the code).

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2021년 2월 3일
ismember('variable_of_interest', who('global'))
  댓글 수: 4
Walter Roberson
Walter Roberson 2024년 1월 26일
ismember('variable_of_interest', who('global'))
detects whether the global variable exists at all, and does not have the side effect of creating the global variable
Stephen23
Stephen23 2024년 1월 26일
"detects whether the global variable exists at all, and does not have the side effect of creating the global variable"
Yes, I am quite aware of that.
The OP makes it clear that they also want to check the value of that global variable. Which this code does not do.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by