Using a global variable within a function

Hi all,
I'm trying to learn how to use global variables, but can't quite get it right:
Im trying to use two buttons, named UpButton and DownButton to control one global variable, p1
A text field, named "Value" displays p1.
Here's my code:
p1 = 0;
ButtonClick("UpButton", p1, 100,"Value");
ButtonClick("DownButton", p1,(-100),"Value");
function ButtonClick(ButtonName,Var,Increment,TextToChange){
                    sym.$(ButtonName).click(function(){
                    Var = Var + Increment;
                    sym.$(TextToChange).html(Var);
However, it seems to be treating p1 as two different variables.
Here's a link to the page to show you what I mean, apologies but this link wont work in google chrome because I'm using dropbox as a server temporarily
In other browsers you may need to click "Show all content" or similar to any security warnings...
https://dl.dropboxusercontent.com/u/83693404/ButtonTest/buttons.html
Here are the project files:
https://app.box.com/s/0shocivto8fl295h62uq
Any help greatly appreciated, sorry if this is a stupid question,
Katherine

Hi Katherine,
However, it seems to be treating p1 as two different variables.
Indeed, your code created two different variables in two different scopes (I guess it as to do with JavaScript closures, but do  not ask me more, I am still a bit foggy about that idiosyncrasy ).
In JavaScript, a primitive parameter – this is the case here with p1, a Number value –, is passed by value. In other words, a copy of the value is made. Your code handles two copies of the value stored in p1.
This contrasts with an object parameter, which is passed by reference (address in memory), without copy. Your code would work if Numbers were passed by reference : the two Var (p1) would then point to the same address.
The intent behind your trial is a global variable.
1) Let us be as simple as possible :
Stage : document.compositionReady event handler
p1 = 0;
buttonClick = function( Increment)
  p1 += Increment;
  sym.$( "Value").html( p1);
Stage : DownButton.click event handler
buttonClick(-100);
Stage : UpButton.click event handler
buttonClick(100);
Without being preceded by the var keyword the variables are global.
So the Number variable p1 can be accessed inside function buttonClick.
And the Function variable buttonClick as well, is accessible inside click event handlers, everything (function definition +function calls) being inside the same symbol (Stage).
2) Now, suppose this is no longer the case : you want to access a variable from another symbol.
We create a new GraySquare symbol, instantiated both in the DownButton symbol (instance name DownSquare) and in the UpButton symbol (instance name DownSquare).
Stage : document.compositionReady event handler
p1 = 0;
sym.buttonClick = function( Increment)
  p1 += Increment;
  sym.$( "Value").html( p1);
The sym. prefix is now necessary to make the variable (here a Function, but you would proceed exactly the same with a String, Number or Boolean) accessible in other symbols.
DownButton symbol : DownSquare.click event handler
sym.getComposition().getStage().buttonClick( -100);
UpButton symbol : UpSquare.click event handler
sym.getComposition().getStage().buttonClick( 100);
From these other symbols, the sym.getComposition().getStage(). prefix is necessary to acces to our global variable (function).
The two examples are downloadable here : https://app.box.com/s/6vkyiqk7i8zwlw0j1wk1
Gil

Similar Messages

  • How to Set and Use a global variable within a session?

    Dear All,
    I'm new to jsp, and would like to ask how to set and use a global variable within a session?
    Thanks in advance.
    Regards,
    Cecil

    With session.setAttribute("name",object) you can store a Attribute in the session object.
    with session.getAttribute("name") you can get it.
    That's it.
    Regards,
    Geri

  • How to use a global variable for reading a query resultset in JDBC lookup?

    Hi Friends,
    Using JDBC lookup, I am trying to read from a table Emp1 using a user defined function. In PI 7.0, this function returns values of a single column only even if you fire a " Select * " query. I am planning to use a global variable(array) that stores individual column values of the records returned by a "select *" query. Need pointers on as to how a global variable can be declared and used to acheive the above scenario. Kindly explain with an example. Any help would be appreciated.
    Thanks,
    Amit.

    Hi Amit,
    Sounds like a good idea but then you would need an external db and update the table in a thread safe way !.
    Regarding your question as to how to work with global variable please refer https://www.sdn.sap.com/irj/scn/weblogs?blog=/pub/wlg/1352. [original link is broken] [original link is broken] [original link is broken]
    Rgds
    joel

  • What is the difference between using a global variable,passing a valuee and using a reference?

    I have created a project that consists of several VIs.  Only the main VI has a front panel and the others perform functions.  The function VIs are dependent on controls on the main VI's front panel.  I have several ways of passing the value of the controls.  One is to use a global variable and just place it on the dependent VIs.  Another option is to strictly connect the terminal from the control to a VI connector block and pass the value directly.  My last option is to create a reference of the control and reference it inside the dependent VIs, but this would also require connections to be made to the VI block.
    What are the advantages/disadvantages of these options?
    -Stephen

    5thGen wrote:
    I have created a project that consists of several VIs.  Only the main VI has a front panel and the others perform functions.  The function VIs are dependent on controls on the main VI's front panel.  I have several ways of passing the value of the controls. 
    1) One is to use a global variable and just place it on the dependent VIs.
    2) Another option is to strictly connect the terminal from the control to a VI connector block and pass the value directly. 
    3) My last option is to create a reference of the control and reference it inside the dependent VIs, but this would also require connections to be made to the VI block.
    What are the advantages/disadvantages of these options?
    -Stephen
    1) Globals are evil and introduce race conditions.
    2) The sub-VI only get the value when it was called and updates that occur while the sub-VI is runing are not sensed by the sub-VI
    3) This uses property node "value" or "value signaling" both of which run the user interface thread which is single-threaded and you incur a thread swap hit to performance. You also have a potential for race conditions.
    The are various methods for sharing dat to/from sub-VI which include Queues and Action Engines.
    I hope that hleps,
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • HOWTO: Declare a variable within a function.

    I'm having a hard time declaring a variable within a function. This is my code:
    CREATE OR REPLACE FUNCTION schemaName.functionName (inParam VARCHAR2(20))
    RETURN VARCHAR2 IS VARCHAR2(10)
    BEGIN
    DECLARE paramLength NUMBER; --This is not working. The docs do not state what the size of the number returned by LENGTH is.
    SELECT LENGTH(inParam) INTO paramLength FROM DUAL;
    IF paramLength < 10 THEN
    RETURN '';
    ELSE
    /* Clean up the value */
    RETURN inParam
    END IF;
    END;

    In relation to your own code...
    CREATE OR REPLACE FUNCTION schemaName.functionName (inParam VARCHAR2(20)) RETURN VARCHAR2 IS
    paramLength NUMBER;
    BEGIN
      /* Clean up the value */
      paramLength = LENGTH(inParam);
      IF paramLength < 10 THEN
        RETURN NULL;
      ELSE
        RETURN inParam
      END IF;
    END; You don't need to use SQL to determine the length of a string.

  • How can I programmatically create and use a global variable?

    I have an app where the number of AI DAQmx tasks I create are specified in a config file.  I have a monitor task that periodically looks at the latest values from all DAQ tasks.  I've been doing this with a set of global variables because it was the simplest way to do it.  But to do this, I have to explicitly create a separate AI task that uses the hard-coded global variable name for the DAQmx samples.  I would prefer to only write one VI for the DAQ loop that writes to a global variable that I programmatically create based on the config file.  The only solution I can think of is to use a global variable "pool" that is sized bigger than I expect to need, and then have a big switch case to select which one I want based on the task index.  But this sounds pretty silly.

    I tend to agree with Ben. I don't buy the concept of taking the asy way out (globals) because it very rarely will things remain static. You almost always have to extend the features and functionality of an application and then you will run into issues with sloppy and lazy implementations. The solutions offered may require a little time to learn but once you do it doesn't really require any extra effort.
    Mark Yedinak
    "Does anyone know where the love of God goes when the waves turn the minutes to hours?"
    Wreck of the Edmund Fitzgerald - Gordon Lightfoot

  • How to declare global variables using another global variable in ODI

    I am declaring a gloabal variable using another global variable.
    say for example:
    I have a global variable empid.
    I am decalaring another global variable empname in refreshing tab of global variables and the select statment is
    select empname from emp where empno = #GLOBAL.empid -------if i write like this i am getting error as invalid character.
    select empname from emp where empno = '#GLOBAL.empid'-------if i write like this i am getting error as invalid number.
    I have kept the datatype as numeric and action as non persistent
    Please help
    Thank you in advance.

    Hi,
    You cant test/refresh empname standalone.
    You need to create a new package drag and drop both variables and make them as refresh variable and execute that package and test.
    Flow,
    empid----> empname
    Thanks,
    Guru

  • Static used on global variable declaration

    I have inherited a CVI project that contains a single .C file and a couple of .UIR files with their associated .H files.
    Many of the global variables have STATIC in their declaration - I believe this is due to the fact the original developer originally had them inside various functions and at some point changed strategy to make them global, leaving the STATIC keyword in place when copy/pasting.
    As I understand it the ONLY implication of STATIC on a global variable would be to keep its visibility only to the .C file in which it is declared. In this instance that is moot since there is only one .C file in the project.
    Is there anything about LabWindows/CVI which I might not be aware of that makes this use of STATIC cause something different than if STATIC were not used?
    Thanks for any input you might have since I'm new to CVI

    Roberto and menchar said it well:
    "static variables are declared at compile time and survive when their block of code terminates. If declared at function level, their value survives from one call of the function to another, so that they can be used over time to store permanent values locale to the function. If declared at module level, they are common to all functions in the module and are allocated outside the stack so that their values are not lost during program life. In every case they can be accessed and modified in values by functions in the program. If arrays, they cannot be dinamically changed in size."
    "The static keyword can be used with a function name also, meaning the function name isn't exported to the linker, and the function is in scope only to code within the module."

  • How to modify global variable in a function?

    Hello,
    I want to modify a globalvariable in a function, at first I did it this way:
    class Global_output_class
    GlobalDim("Correlation_Status,fail_part,End_Exp")
    dim pouet
    Correlation_Status = 12
    Call Correlation()
    pouet = Correlation_Status
    Function Correlation()
    Dim Global_output_class_sub
    Set Global_output_class_sub = new Global_output_class
    Correlation_Status = 1
    fail_part = 2
    End_Exp = 3
    Global_output_class_sub.CorrelationStatus = Correlation_Status
    Global_output_class_sub.failpart = fail_part
    Global_output_class_sub.EndExp = End_Exp
    set Correlation = Global_output_class_sub
    End function
    In this case: correlation_status receive the value 12, then I go to my function correlationn() where it became 1
    Then it goes out of the subfunction and takes the previous value from the program(12) ( I dont want that)
    To solve the problem I made it this way:
    class Global_output_class
    public CorrelationStatus
    public failpart
    public EndExp
    end class
    GlobalDim("Correlation_Status,fail_part,End_Exp")
    Correlation_Status = 12
    Set Global_Output = Correlation()
    Correlation_Status = Global_Output.CorrelationStatus
    fail_part = Global_Output.failpart
    End_Exp = Global_Output.EndExp
    pouet = Correlation_Status
    Function Correlation()
    Dim Global_output_class_sub
    Set Global_output_class_sub = new Global_output_class
    Correlation_Status = 1
    fail_part = 2
    End_Exp = 3
    Global_output_class_sub.CorrelationStatus = Correlation_Status
    Global_output_class_sub.failpart = fail_part
    Global_output_class_sub.EndExp = End_Exp
    set Correlation = Global_output_class_sub
    End function
    This way my global value are recopied in themselves after leaving the subprogram
    I got a lot of variables, is there any easier way so the global variable modified in a function keep the value after leaving the function?
    Thanks for help,
    Fred
    Solved!
    Go to Solution.

    Hi Fred,
    it is possible to use a global defined variable but the better way is to use to use a funtion call (or procedure call) with parameters. Please find first the good solution for a funcion call with parameter and the sub-optimal way with an global valiable:
    dim oParameter
    set oParameter = new cGlobal_output_class
    oParameter.Correlation_Status = 12
    msgbox "Correlation_Status before Call Correlation: " & oParameter.Correlation_Status
    Call Correlation(oParameter)
    msgbox "Correlation_Status after Call Correlation: " & oParameter.Correlation_Status
    Function Correlation(oPara)
    msgbox "Correlation_Status in the FUNCTION before change: " & oPara.Correlation_Status
    oPara.Correlation_Status = 1
    oPara.fail_part = 2
    oPara.End_Exp = 3
    msgbox "Correlation_Status in the FUNCTION after change: " & oPara.Correlation_Status
    End function
    class cGlobal_output_class
    dim Correlation_Status,fail_part,End_Exp
    end class
    call GlobalDim("oPouet")
    dim oPouet
    set oPouet = new cGlobal_output_class
    oPouet.Correlation_Status = 12
    msgbox "Correlation_Status before Call Correlation: " & oPouet.Correlation_Status
    Call Correlation()
    msgbox "Correlation_Status before Call Correlation: " & oPouet.Correlation_Status
    Function Correlation()
    msgbox "Correlation_Status in the FUNCTION before change: " & oPouet.Correlation_Status
    oPouet.Correlation_Status = 1
    oPouet.fail_part = 2
    oPouet.End_Exp = 3
    msgbox "Correlation_Status in the FUNCTION after change: " & oPouet.Correlation_Status
    End function
    class cGlobal_output_class
    dim Correlation_Status,fail_part,End_Exp
    end class
    Greetings
    Walter

  • Application Builder - Use of Global Variables

    Hello,
    I have an application which consists one one main VI running for the user interface, and one VI running in the background dealing with CAN communications.  These two VIs must communicate using global variables.  In the main VI, I have to open a reference to the global variable VI in order to write data to it.  The application works correctly in LabVIEW environment.  However when I build the application using application builder, I receive an error with the open reference VI in opening the global variable VI.  The error given is Error Code 7: File not found.  The path to the Global variable VI is correct however.  I am pretty sure of this because in my main VI, I open up other VIs based on the open reference function and a path.
    Therefore:
    1) I can open references to normal VIs and use properties such as run VI without a problem.
    2) This does not work for my global variable vi.
    Build settings:
    Im dont understand all the build options completely but the settings I use are:
    1) Single target file contening all the VIs
    2) All the VIs I use are located in the same folder
    I hope the explaination is clear enough.
    Do you have any suggestion to explain what happens and how can I make it work correctly?
    Thanks
    Julien

    Duplicate.
    Try to take over the world!

  • Applicatio​n Builder - Use of Global Variables

    Hello,
    I have an application which consists one one main VI running for the user interface, and one VI running in the background dealing with CAN communications.  These two VIs must communicate using global variables.  In the main VI, I have to open a reference to the global variable VI in order to write data to it.  The application works correctly in LabVIEW environment.  However when I build the application using application builder, I receive an error with the open reference VI in opening the global variable VI.  The error given is Error Code 7: File not found.  The path to the Global variable VI is correct however.  I am pretty sure of this because in my main VI, I open up other VIs based on the open reference function and a path.
    Therefore:
    1) I can open references to normal VIs and use properties such as run VI without a problem.
    2) This does not work for my global variable vi.
    Build settings:
    Im dont understand all the build options completely but the settings I use are:
    1) Single target file contening all the VIs
    2) All the VIs I use are located in the same folder
    I hope the explaination is clear enough.
    Do you have any suggestion to explain what happens and how can I make it work correctly?
    Thanks
    Julien

    Your usage sounds very weird. Normally, the best reason to use a standard global is that it's easy to use. You simply place it in the diagram and select the one you want. Your use case of opening a reference to the VI sounds weird.
    You say that the path is correct. There is a very simple way to check this. Place a path indicator showing the path you built and you will see exactly. The most common reason for path problems in executables is if you build relative paths since the executable itself is treated as another directory, so you have an extra level. The common way to go around this is to use the Application.Kind property and if you're running in the RTE perform an extra strip. Another problem you might have is that if you are dynamically loading the VI, it will not get included in the build automatically. You have to include it manually either by selecting it as a support file or by including a VI which calls it normally.
    After all that, though, my suggestion would simply be to avoid the global. If you need inter-VI communication you can use a lot of other global options like LV2 globals, named queues, notifiers, etc. or even use globals as they were intended and they will all probably be simpler than the way you currently use globals. Note that global communication in LabVIEW is very risky because you can easily create race conditions and it's important to look out for that.
    Try to take over the world!

  • Use of global variables like g_cnt_transactions_transferred in the LSMW

    Hi SapAll.
    when i had a look at the some of the LSMW's whic use IDOC as the object of uploading data into SAP from external Files i have found in the coding under the step "Maintain Field Mapping and Conversion Rules" that they use some of the global variables like below
    .if p_trfcpt = yes or sy-saprl >= '46A'.
      EDI_DC40-DOCNUM = g_cnt_transactions_transferred + 1.
    endif.
    .EDI_DC40-CIMTYP = g_cimtyp.
    .EDI_DC40-MESTYP = g_mestyp.
    .EDI_DC40-MESCOD = g_mescod.
    .if p_filept = yes.
      EDI_DC40-SNDPOR = g_fileport.
    elseif p_trfcpt = yes.
      EDI_DC40-SNDPOR = g_trfcport.
    endif.
    my doubt is where i can find these variables 'g_cnt_transactions_transferred ','g_cimtyp','g_mescod','g_fileport','g_trfcport' in the LSMW and what is the use of the variable  'g_cnt_transactions_transferred ' in the LSMW.
    I have treid to find out the above listed variables looking in step 'Maintain Field Mapping and Conversion Rules' under global variabels list and the other lists also but i couldnt found.
    can any one help me in this ?
    regards.
    Seetha.

    Hi Seetha,
               In the LSMW Workbench go to the option user menu.  And check the option display conversion program.
    Now when you execute with the radio button on dislplay conversion program, you ll see the code that got generated in the background while you built your LSMW.
    The global variables that you have mentioned are bound to be there in this program generated in the background..
    You can put a break point here and see for yourself what the value of these global variables are at runtime.
    File port, TRFC port , no. of transactions executed by one run of the LMSW Idoc program , message type are some of the fields that you have asked for .
    Regards,
    Arun

  • [Bash] How to `declare` a global variable inside a function?

    #!/bin/bash
    # Not using declare -A, array will be treated as indexed array rather than an associative array
    seta()
    for ((n=0;n<$1;n++)); do
    printf -v a_$n[k] %s k$n
    printf -v a_$n[j] %s j$n
    eval echo inside seta: a_$n[k] = \$\{a_$n\[k\]\}
    done
    seta 3
    echo outside: a_0[k] = ${a_0[k]}
    echo outside: a_0[j] = ${a_0[j]}
    echo
    # Use declare -A inside function, array will be undefined outside
    setb()
    for ((n=0;n<$1;n++)); do
    declare -A b_$n # Note here
    printf -v b_$n[k] %s k$n
    printf -v b_$n[j] %s j$n
    eval echo inside setb: b_$n[k] = \$\{b_$n\[k\]\}
    done
    setb 3
    echo outside: b_0[k] = ${b_0[k]}
    echo outside: b_0[j] = ${b_0[j]}
    echo
    # The bad solution, only works if we know beforehand how many c_? arrays will be assigned inside setc()
    for ((n=0;n<3;n++)); do
    declare -A c_$n
    done
    setc()
    for ((n=0;n<$1;n++)); do
    printf -v c_$n[k] %s k$n
    printf -v c_$n[j] %s j$n
    eval echo inside setc: c_$n[k] = \$\{c_$n\[k\]\}
    done
    setc 3
    echo outside: c_0[k] = ${c_0[k]}
    echo outside: c_0[j] = ${c_0[j]}
    My original code does the declare -A as in setb(). I was surprised when I saw all blank output... Now the problem is illustrated clearly by the setb() example.
    The setc() example works, but a bit ugly: look at the two 3's...
    My ideal solution would be, something like `declare_global -A b_$n` in setb()
    Any ideas?

    with current bash versions, i don't think it is possible to declare global associative arrays in functions.
    what you are after is the "-g" option of typeset which is available in zsh.
    i think i read somewhere that something similar may be planned for bash 4.2.

  • Is it possible to use a Shared Variable within a Chart?

    I have a shared variable between a container report and a subreport called {@ResponseCount}:
    whileprintingrecords;
    shared numbervar Responses:= DistinctCount ({Survey_Response.RecipID})
    I placed the variable in the report footer and the value is passing correctly.  I would like to use this shared value in a chart; however, it is not even listed in the Chart Expert as an available field.  I was placing the chart in Report Footer b.
    I have also tried moving the variable value to the Report Header and placing the chart in the Report Footer, with the same result.
    I tried changing the variable to a global variable, thinking that I was using the incorrect scope, but that passed a zero value instead.
    Any suggestions would be welcome.  Thank you.

    Thank you for the response.  Though I almost gave up on this, I did find a way to access the shared variable after all.  I created a formula that simply called the variable formula.  For this example, I was using a shared variable to pull a value from my container report into my sub report for use in a chart.
    In my container report I created the shared variable {@Get_Responses}:
    whileprintingrecords;
    shared numbervar Responses:= DistinctCount ({Survey_Response.RecipID})
    In my sub report I created the formula to call the above variable {@Fetch_Responses}
    whileprintingrecords;
    shared numbervar Responses;
    Then, again in my sub report, I created a second formula to call the above formula {@ResponsesForChart}
    {@Fetch_Responses}
    This last formula was then available for use in the chart I needed to create.

  • Change a global variable with a function

    HI ALL!
    I have the following problem...
    I would like to change a global variable with a void function so not like this: variable = function(); .
    What do you suggest?
    Best regards,
    Korcs

    I have the following problem...
    I would like to change a global variable with a void
    function so not like this: variable = function(); .
    What do you suggest?>
    >
    I dont quite understand your question but if your variable is a reference to an object then you can certainly have a method to alter the object that the reference is pointing to and/or the reference itself..
    otherwise your 'function' will have to return the same type as the variable itself in order to do the assignment as you demonstrated, regardless of wether it's C, C# or Java, AFAIK, WIRNM
    HTH

Maybe you are looking for

  • Can I sync x20 different Indesign set ups in one go?

    Is it possible to manage and sync a whole company's Indesign workspaces from a single point? Currently, it has been set up so all individuals have their own login / password to Creative Cloud. However, we'd really like to be able to sync a MAIN unifi

  • IBY_DISBURSE_UI_API_PUB_PKG - package is corrupted..

    Hi, oracle e business suite 12.0.3 the following named package body id corrupted if anyone has this same version - package body - will be fine. awiaiting for your reply Regards MKTS [email protected]

  • Using Address Book, distribution list contact does not appear

    Using 10.7.4, added a name to an address book distribution list but it does not appear in the email "to" address. Had added to people previously and it worked fine but not with the last entry. Verified that the contact's name, address, etc. all corre

  • Aren't Safari bookmarks supposed to sync between computers?

    I think that Safari bookmarks are suppose to be the same across all of one's computers running the same OS. But that is not the case between my iMac running OS X Mountain Lion and my MacBook Pro running OS X Mountain Lion. Any help?

  • Embedding CRL in a digital signatue

    I checked the "include signature's status when signing" and created a new signature. My certificate hierarchy includes my certificate, my issuer certificate that is a subordinate CA, and the root certificate that is the issuer of my issuer. The CDP b