Author Topic: Duda con variables Locales y Globales  (Read 1629 times)

Offline mentalthink

  • Prof. Inline
  • *****
  • Posts: 3366
  • Integrated Brain
    • View Profile
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.

Offline Slydog

  • Prof. Inline
  • *****
  • Posts: 930
  • KodeSource
    • View Profile
    • KodeSource
Re: Duda con variables Locales y Globales
« Reply #1 on: 2011-Aug-12 »
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
« Last Edit: 2011-Aug-12 by Slydog »
My current project (WIP) :: TwistedMaze <<  [Updated: 2015-11-25]

Offline mentalthink

  • Prof. Inline
  • *****
  • Posts: 3366
  • Integrated Brain
    • View Profile
Re: Duda con variables Locales y Globales
« Reply #2 on: 2011-Aug-12 »
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

Offline Slydog

  • Prof. Inline
  • *****
  • Posts: 930
  • KodeSource
    • View Profile
    • KodeSource
Re: Duda con variables Locales y Globales
« Reply #3 on: 2011-Aug-12 »
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]

Offline mentalthink

  • Prof. Inline
  • *****
  • Posts: 3366
  • Integrated Brain
    • View Profile
Re: Duda con variables Locales y Globales
« Reply #4 on: 2011-Aug-13 »
Thanks for the fantastic explanation, now I have understand Static perfectly,  :nw: :nw:   :booze:

Thanks,
Iván J.