Duda con variables Locales y Globales

Previous topic - Next topic

mentalthink

Hola perdonad por otra pregunta, que seguro será una tonteria, pero como mis conocimientos de programación, son más bien escasos, quería haceros está pregunta:

En una funcion, en la que pongo por ejemplo:

FUNCTION my_func:
local a
inc a,1
...
...
endfunction

la variable a, no incrementa, supongo que es que cada vez que hace el bucle, a vale 0

he probado haciendo que la variable a, en vez de ser local sea Global (funciona), pero desconozco si esto es correcto, ya que dentro de una parte o "encapsulado" no creo que sea muy lícito declarar una variable Global, a parte de poder hacerlo al principio del programa y ahorrar recursos.

Un saludo,
Iván J.

Slydog

#1
Use the 'STATIC' keyword for what you want.
STATIC variables are only visible in the function that they are declared, and they keep their value between function calls.

So your example would be:
Code (glbasic) Select
FUNCTION my_func:
    STATIC a
    INC a, 1
ENDFUNCTION


[Edit] If you want your variable to be initialized the first time it is used you can specify that with:
(ie: it does NOT get set to '10' each time you call the function, just the first time)
Code (glbasic) Select
    STATIC a = 10
My current project (WIP) :: TwistedMaze <<  [Updated: 2015-11-25]

mentalthink

Hi Slydog, I don´t rebember this command, I think I have to review the help of Glbasic.

And then, in functions if the variable don´t changes, it´s better use Static or use Local?¿.

Thanks again

Slydog

Use STATIC when you want the function to remember the value for the next call.
Use LOCAL when the variable is only used during that call, and you have no need to remember for next time.

STATIC behaves 'like' a LOCAL variable: in that they are both belong to a function.
STATIC behaves 'like' a GLOBAL variable: in that it always remembers the latest value, except it can ONLY be accessed from the FUNCTION that declared it.
My current project (WIP) :: TwistedMaze <<  [Updated: 2015-11-25]

mentalthink

Thanks for the fantastic explanation, now I have understand Static perfectly,  :nw: :nw:   :booze:

Thanks,
Iván J.