Uso de procedimientos, funciones y propiedades

A continuación se describe el uso básico de los procedimientos, las funciones y las propiedades de LibreOffice BASIC.

Icono de nota

Cuando crea un módulo nuevo, LibreOffice BASIC inserta automáticamente una Sub llamada «Main». Este nombre predeterminado no tiene nada que ver con el orden o el punto de arranque de un proyecto de LibreOffice BASIC. Además, es seguro cambiar el nombre de esta Subrutina.


Icono de nota

Se aplican algunas restricciones a los nombres de sus variables públicas, subrutinas, funciones y propiedades. No debe emplear el mismo nombre que otro de los módulos de la misma biblioteca.


Procedures (Subroutines) functions (Function) and properties (Property) help you maintaining a structured overview by separating a program into logical pieces. These pieces can be easily reused to perform similar tasks in other projects.

Pasar variables a procedimientos, funciones o propiedades

Se pueden pasar variables tanto a procedimientos como a funciones o propiedades. Se debe declarar qué parámetros espera la Sub, Function o Property:


  Sub SubName(Parameter1 As TYPENAME, Parameter2 As TYPENAME,...)
      ' su código va aquí
  End Sub

Se llama a la Sub mediante la sintaxis siguiente:


  [Call] SubName( [Parameter1:=]Value1, [Parameter2:=]Value2, ...)

The parameters passed to a Sub must fit to those specified in the Sub declaration.

The same process applies to a Function. In addition, functions always return a result. This result is defined by assigning the value to return to the function name:


  Function FunctionName(Parameter1 As TYPENAME, Parameter2 As TYPENAME,...) As TYPENAME
      ' su código va aquí
      FunctionName=Result
  End Function

Se llama a la Function mediante la sintaxis siguiente:


  Variable = FunctionName( [Parameter1:=]Value1, [Parameter2:=]Value2, ...)

Properties combine the syntax of procedures and functions. A Property usually requires up to one parameter.


  Private _IsApproved As TYPENAME
  Property Get IsApproved As TYPENAME
      ' su código va aquí
      IsApproved = some_computation
  End Property
  Property Let IsApproved(value As TYPENAME)
      ' su código va aquí
      _IsApproved = computed_value
  End Property

Se llama a la Property mediante la sintaxis siguiente:


  var = IsApproved
  IsApproved = some_value
Icono de consejo

También puede utilizar el nombre completo para llamar a un procedimiento, función o propiedad:
[Call] Library.Module.Macro(), donde Call es facultativo.
Por ejemplo, para llamar a la macro Autotext desde la biblioteca Gimmicks, use la orden siguiente:
Gimmicks.AutoText.Main()


Pasar variables por valor o por referencia

Parameters can be passed to a procedure, a function or a property either by reference or by value. Unless otherwise specified, a parameter is always passed by reference. That means that a Sub, a Function or a Property gets the parameter and can read and modify its value.

If you want to pass a parameter by value insert the key word ByVal in front of the parameter when you call a Sub, a Function or a Property, for example:


  Function ReadOnlyParms(ByVal p2, ByVal p2)
      ' su código va aquí
  End Function
  result = ReadOnlyParms(parm1, parm2)

In this case, the original content of the parameter will not be modified by the Function since it only gets the value and not the parameter itself.

Definir parámetros opcionales

Es posible definir funciones, procedimientos o propiedades con parámetros opcionales; por ejemplo:


  Sub Rounding(number, Optional decimals, Optional format)
      ' su código va aquí
  End Sub

Argumentos posicionales o de palabra clave

Al llamar a una función o subrutina, puede pasar sus argumentos por posición o por nombre. El paso por posición consiste simplemente en enumerar los argumentos en el orden en que están definidos los parámetros en la función o subrutina. El paso por nombre requiere anteponer al argumento el nombre del parámetro correspondiente, seguido de dos puntos y un signo de igualdad (:=). Los argumentos de palabra clave pueden aparecer en cualquier orden. Consulte la función Replace() de BASIC para ver ejemplos de este tipo.

When needing to pass less parameters, use keywords arguments. Passing values for fewer parameters by position requires to supply values for all parameters before them, optional or not. This ensures that the values are in the correct positions. If you pass the parameters by name - using keyword arguments - you may omit all other intermediate arguments.

Ámbito de variables

A variable defined within a Sub, a Function or a Property, only remains valid until the procedure is exited. This is known as a "local" variable. In many cases, you need a variable to be valid in all procedures, in every module of all libraries, or after a Sub, a Function or a Property is exited.

Declaring Variables Outside a Sub a Function or a Property


Global VarName As TYPENAME

La variable es válida mientras dure la sesión de LibreOffice.


Public VarName As TYPENAME

La variable es válida en todos los módulos.


Private VarName As TYPENAME

La variable solo es válida en este módulo.


Dim VarName As TYPENAME

La variable solo es válida en este módulo.

Ejemplo para variables privadas

Fuerce que las variables privadas lo sean en todos los módulos estableciendo CompatibilityMode(True).


  ' ***** Module1 *****
  Private myText As String
  Sub initMyText
      miTexto = "Hola"
      Print "En módulo1 : ", miTexto
  End Sub
   
  ' ***** Module2 *****
  'Option Explicit
  Sub demoBug
      CompatibilityMode( True )
      initMyText
      ' Ahora devuelve una cadena vacía
      ' (o produce un error con Option Explicit)
      Print "Ahora en módulo2 : ", miTexto
  End Sub

Guardar el contenido de una variable luego de salir de una Sub, una Function o una Property


  Static VarName As TYPENAME

The variable retains its value until the next time the a Function, Sub or Property is entered. The declaration must exist inside a Sub, a Function or a Property.

Specifying the Return Value Type of a Function or a Property

As with variables, include a type-declaration character after the function name, or the type indicated by As and the corresponding data type at the end of the parameter list to define the type of the function or property's return value, for example:


  Function WordCount(WordText As String) As Integer
¡Necesitamos su ayuda!

¡Necesitamos su ayuda!