Page 1 of 2

Cantidad variable de parámetros

PostPosted: Thu Nov 27, 2014 8:29 am
by Antonio Linares
Cuando necesiteis llamar a una función y proporcionarle un número variable de parámetros podeis usar:

function MyFunc( ... )

y entonces llamar a hb_aparams() para obtener un array con todos ellos :-)

Re: Cantidad variable de parámetros

PostPosted: Thu Nov 27, 2014 10:22 am
by fgondi
Muchas gracias por la información, Antonio

Re: Cantidad variable de parámetros

PostPosted: Thu Nov 27, 2014 5:36 pm
by Carlos Mora
Antonio,

En general no es imprescindible indicar ni siquiera que parámetros pasas, a menos que quieras ponerle un nombre ;) , pero si vas a usar hb_aparams, o HB_PValue(), ni siquiera hace falta indicarlo con '...' .

HB_PValue(i) devuelve el parámetro i-ésimo, y sabremos cuantos parámetros hay con PCount().

Por ejemplo:

? Expand( 'Select * from clientes where id = $1', 22 ) -> Select * from clientes where id = 22

FUNCTION Expand( cQuery ) // Aunque escribiendo (cQuery, ... ) hace más obvio que tiene parámetros variables
LOCAL i
i:= PCount()
WHILE i > 1
cQuery:= StrTran( cQuery, '$'+(LTrim(Str(i-1))), ClipValue2SQL( HB_PValue(i) ) )
i--
ENDDO

RETURN cQuery

Se pueden hacer cosas bastante majas...

Re: Cantidad variable de parámetros

PostPosted: Thu Nov 27, 2014 5:59 pm
by Antonio Linares
Carlos,

gracias por la información :-)

Dudo que Przemek pasará por alto algo asi. Tal vez haya otro uso para "..." que desconocemos.

Si os parece importante lo podemos preguntar en la lista de desarrollo de Harbour

Re: Cantidad variable de parámetros

PostPosted: Fri Nov 28, 2014 8:53 am
by Carlos Mora
Solo se me ocurre una cuestion de orden y elegancia, una forma de hacer explícito el hecho de que vas a usar parámetros.
Tal vez el pcode generado podría llegar a mostrar alguna diferencia, no se...

Pero en lo personal lo he usado bastante, como en el ejemplo, y como podrás adivinar, con uso intensivo (es en las querys) y va fenomenal.

Y para añadir más cosas a la colección de cositas guapas, por si alguno todavía no lo conoce, van los siguientes #pragmas:

Code: Select all  Expand view

#xcommand TEXT INTO <v> => #pragma __cstream|<v>:=%s
#xcommand TEXT INTO <v> ADDITIVE => #pragma __cstream|<v>+=%s
 


Esto nos permite escribir texto literal, que incluya incluso saltos de línea, como en:

Code: Select all  Expand view

   TEXT INTO cTexto

      CREATE TABLE IF NOT EXISTS `validalta` (
        `id`         int(11) NOT NULL AUTO_INCREMENT,
        `fechanaci`  date,
        `nif`        varchar(9)  DEFAULT NULL,
        `mail`       varchar(50) DEFAULT NULL,
        `cuenta`     varchar(4) DEFAULT NULL,
        PRIMARY KEY (`id`),
        UNIQUE KEY `NIF` (`nif`)
      );
   ENDTEXT

   oServer:Command( cTexto )
 


o bien, XML combinado con la funcioncita de Expand

Code: Select all  Expand view

               TEXT INTO cTransac
                  <tns:importAbsenceFiles xmlns:tns="http://echange.service.open.server.com">
                     <tns:absenceFilesToImport>
                        <tns:absenceFile>
                           <tns:absenceTypeAbbreviation>VACAC</tns:absenceTypeAbbreviation>
                           <tns:employeeIdentificationNumber>$1</tns:employeeIdentificationNumber>
                           <tns:startDate>$2</tns:startDate>
                           <tns:endDate>$3</tns:endDate>
                        </tns:absenceFile>
                     </tns:absenceFilesToImport>
                  </tns:importAbsenceFiles>
               ENDTEXT

               cTransac:= Expand( cTransac, oQuery:dni, oQuery:FechaInicio, oQuery:FechaFin )

 


Como te decía, entre SQL, XML y web... lo uso de forma intensiva, y ayuda a hacer la programación muchísimo más clara.

Re: Cantidad variable de parámetros

PostPosted: Fri Nov 28, 2014 2:40 pm
by Antonio Linares
Carlos,

Muy bueno :-)

Muchas gracias por compartirlo :-)

Re: Cantidad variable de parámetros

PostPosted: Fri Nov 28, 2014 9:19 pm
by Carles
Carlos --> Bravo, bonissimo para mi, no lo conocia.... :lol:

(Copy/paste cagando leches....)


Gracias !!!

Re: Cantidad variable de parámetros

PostPosted: Fri Nov 28, 2014 9:46 pm
by csincuir
Cada día de aprende algo nuevo!
Gracias tocayo, muy bueno, me serán de bastante utilidad tus ejemplos.

Saludos.

Carlos.

Re: Cantidad variable de parámetros

PostPosted: Sat Nov 29, 2014 8:37 am
by Baxajaun
Carlos,

muchísimas gracias por compartir la información y los ejemplos.

Saludos

Re: Cantidad variable de parámetros

PostPosted: Sat Nov 29, 2014 10:35 am
by cnavarro
Carlos
Gracias, es muy bueno

Re: Cantidad variable de parámetros

PostPosted: Sat Nov 29, 2014 12:50 pm
by AngelSalom
Uau, uau, uau .. esos #pragma son la repera !! :D :D

Re: Cantidad variable de parámetros

PostPosted: Mon Dec 01, 2014 9:18 am
by fgondi
Carlos, muy, pero que muy bueno

Fácil de leer en el código fuente, facil de copiar y pegar para probar la consulta sql.

Increíble.

Re: Cantidad variable de parámetros

PostPosted: Mon Dec 01, 2014 9:34 am
by Antonio Linares
Si os parece incluimos esos pragmas en FiveWin.ch :-)

Controlando que sea Harbour, porque imagino que no funcionan en xHarbour

Re: Cantidad variable de parámetros

PostPosted: Mon Dec 01, 2014 9:35 am
by Antonio Linares
Code: Select all  Expand view
#ifndef __XHARBOUR__
   #xcommand TEXT INTO <v> => #pragma __cstream|<v>:=%s
   #xcommand TEXT INTO <v> ADDITIVE => #pragma __cstream|<v>+=%s
#endif
 

Re: Cantidad variable de parámetros

PostPosted: Mon Dec 01, 2014 3:00 pm
by carlos vargas
Antonio, no se como lo maneja xharbour internamente, pero segun la ayuda
Syntax
TEXT [TO PRINTER] [TO FILE <fileName>]
<text>
ENDTEXT

or

TEXT INTO <varName>
<text>
ENDTEXT

Arguments
TO PRINTER
The text is additionally output to the printer.
TO FILE <fileName>
The text is additionally output to the file <fileName>. It can be specified as a literal file name or as a character expression enclosed in parentheses. The default extension is TXT.
INTO <varName>
This is the symbolic name of the variable to assign <text> to.
<text>
This is a literal text block enclosed in TEXT and ENDTEXT. The text is output to the screen and displayed exactly as written in the PRG source code file. Description
The TEXT...ENDTEXT command outputs a block of literal text to the console. Output can be directed additionally to a printer or a file. When SET CONSOLE is set to OFF, the screen output is suppressed.
ALternatively, the text is assigned as character string to the variable <varName> when the INTO option is used.