Variable not updating?

Posted by Mike.mac.kenzie on Tue 13 Feb 2024 04:15 AM — 5 posts, 12,271 views.

#0
So I'm trying to use variables to do some different things, but I'm having a problem with variables not updating. When I use the following code, it always notes the variables as the same thing even though I have changed the variable to a new thing.

SetVariable("thing", "1")
Note("@thing") -- shows 1
SetVariable("thing", "2")
Note("@thing") -- shows 1

then when I run that again, both notes show as 2 instead of one. How do I get the proper numbers to show?
USA Global Moderator #1
Nobody should ever use the @thing notation for variables inside script code, because basically nobody understands what it actually does, what it's for, and when to not use it.

Use Note(GetVariable("thing")) instead and it will do what you expect.
Amended on Tue 13 Feb 2024 05:17 AM by Fiendish
#2
What if I wanted to update the variable and then run an ifcheck on it right after? How would I get that to work correctly?

SetVariable("thing", "1")
if @thing == 1 then
Send("dosomething")
end

Wont this also not work correctly?
Australia Forum Administrator #3

The expanding of variables is done at the start of script execution. Thus, changing a variable and testing it in the same script will always return the original variable contents.

So this won’t work:

SetVariable("thing", "1")
if @thing == 1 then
    Send("dosomething")
end

This will:

SetVariable("thing", "1")
if GetVariable ("thing") == "1" then
    Send("dosomething")
end

Note that variables are stored as strings, not numbers, which is why I quoted the “1”.

What is easier anyway is to use Lua variables, if you don’t need them to persist from one session to another, ie.

thing = 1
if thing == 1 then
    Send("dosomething")
end
Amended on Tue 13 Feb 2024 09:12 PM by Nick Gammon
Australia Forum Administrator #4
Here is a video explaining variables in general:

http://www.gammon.com.au/forum/?id=10863