I have found myself wanting to do certain things in my programs only if a variable has changed. I have so far been doing something like this:
int x = 1;
int initialx = x;
...//code that may or may not change the value of x
if (x!=initialx){
    doOneTimeTaskIfVariableHasChanged();
    initialx = x; //reset initialx for future change tests
}  
Is there a better/simpler way of doing this?
There are multiple ways to do it. Use a Value Instance and use the Changed or PropertyChanged event to do it. Use the __newindex metamethod in a metatable to do it.
When you reassign a variable to another value, it simply changes the reference to that new value and becomes bound to it.
A variable is a data item whose value can change during the program's execution.
It is called a variable because the value may vary between data units in a population, and may change in value over time.
Example:
create a variable with the same name with a number.
int var1;
int var2;
if(var1 != var2)
{
//do the code here
var2 = var1;
}
hope this help.
Since you want to find and perform some action only if the value changes, I would go with setXXX, for example:
public class X
{
    private int x = 1;
    //some other code here
    public void setX(int proposedValueForX)
    {
       if(proposedValueForX != x)
       {
           doOneTimeTaskIfVariableHasChanged();
           x = proposedValueForX;
       }
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With