Page 1 of 1

Confused with local variable usage

Posted: Wed Jul 02, 2014 9:59 pm
by Weaksafety
Hi,

I'm trying to set a local variable in a card script, so that I can update its value and get it as needed.

On the card script I've written:

Code: Select all

local thisVar = 23

on tryThis
   answer thisVar
end tryThis


In the same card there's a button that does this:

Code: Select all

on mouseUp
   put 21 into thisVar
   tryThis
end mouseUp
If I click on the button, '23' is answered instead of '21'. I suppose it's because I should tell Livecode that the value of thisVar should be looked up the card script, but I can't find a solution.
What am I doing wrong?

Thanks a mil! :D

Re: Confused with local variable usage

Posted: Wed Jul 02, 2014 10:12 pm
by magice
the problem, is that you applied the new value from a different script (the button)
try this

in the card script:

Code: Select all

function tryThis tX
  put tX into thisVar
return thisVar
 end tryThis
now call it from the button like this

Code: Select all

on mouseUp
answer tryThis(25)
end mouseUp
untested so might contain typos. The idea is to pass the variable from your button to the card script through a function.

Re: Confused with local variable usage

Posted: Wed Jul 02, 2014 10:23 pm
by Weaksafety
Thanks, I'm still doubtful on one thing though: how can I update the value of a local variable, declared at the card level, from an object on the same card?
Do I need to create a function on the card that's tasked to update the value, or is there a quicker way?
:D

Re: Confused with local variable usage

Posted: Wed Jul 02, 2014 10:30 pm
by magice
Weaksafety wrote:Thanks, I'm still doubtful on one thing though: how can I update the value of a local variable, declared at the card level, from an object on the same card?
Do I need to create a function on the card that's tasked to update the value, or is there a quicker way?
:D
actually what I usually do, is use a custom property of the card, but a function works.

Re: Confused with local variable usage

Posted: Wed Jul 02, 2014 11:59 pm
by dunbarx
Hi.

Try this: Make a button and a field on a new card. Put this in the button script:

Code: Select all

local xx

on mouseUp
   add 1 to xx
   put xx into fld 1
end mouseUp
And the same thing in the card script.

Now hit the button several times. Then click somewhere on the card a few times. The variable "xx" is only local to the scripts it resides in, not across scripts. For that you need a global, or as Magice says, and I agree, a custom property. Do you have experience with these? They are just wonderful, and they even survive sessions. Write back if you need advice.