Diferencia entre revisiones de «Gambas/Scripting con Gambas»

Contenido eliminado Contenido añadido
Sin resumen de edición
Sin resumen de edición
Línea 10:
== '''Gsb2 - En la consola de Linux''' ==
*'''Hola Mundo con Scripting en Gambas'''
Esta característica es provista por la utileriautilería ''gbs2'', que es un pequeño ejecutable de Gambas que permite vaciar cualquier código de Gambas en un archivo de texto.
Antes que nada debes asegurarte que el scripter ''gbs2'' esta instalado en alguna parte de tu sistema. Teclea en la linea de comandos o consola de tu distribución de Linux:
user@PC:~$ '''which gbs2'''
''/usr/bin/gbs2''
user@PC:~$
 
Despues abre el Editor de Codigo de Gamabs y tu editor de texto favorito. Crea un archivo llamado ''holamundo.gbs'' en el directior ''home''. Inserta las siguientes lineas a tu archivo:
{{Consejo| En Linux, como tal vez ya sepas, no es necesario agregar una extensión (de 3 o 4 caracteres) al nombre del archivo. Sin embargo, para identificar mas rápidamente tus scripts de Gambas de esta sección te recomiendo agregarle el .gbs}}
#!/usr/bin/env gbs2
'This script is will print Hello World on the screen
DIM text AS String = "Hola Mundo con Scripting en Gambas"
PRINT text
Línea 27 ⟶ 26:
 
Ahora ejecuta el script en la consola de Linux tecleando el nombre del script.
user@PC:~$ '''holamundo.gbs'''
''Hola Mundo con Scripting en Gambas''
user@PC:~$
{{Consejo| Si el comando no se ejecuta y en cambio recibes un mensaje de error, intenta ejecutarlo asi ''gbs2 holamundo.gbs''}}
 
*'''Ejecutar comandos y aplicaciones'''
Executing commands
Una de las tareas mas comunes de los scripts es ejecutar otras aplicaciones y comandos del sistema. El siguiente script muestra el contenido del directorio actual pero ignorando los owners y los archivos de respaldo. Llama a este archivo ''ls.gbs''.
One of the common tasks of scripts is to run other applications and to execute system commands. Now, you'll write a script to display the content of the current directory but ignoring the owners and the backup files. Name the file ls.gbs.
#!/usr/bin/env gbs2
DIM argcommand AS NEW String[]
'This script display the content of the current directory
command.Add("-Bls")
' ignoring backup files and the owners
DIM command AS NEW String[].Add("-B")
command.Add("ls-g")
PRINT "------ USING SHELLEXEC ------"
command.Add("-B")
EXEC command.Add("-g")
PRINT "------ USING EXECSHELL ------"
SHELL "ls -B -g"
EXEC command
De hecho, si teclearas directamente en la consola el comando ''ls -g -B'' obtendrías el mismo resultado que ejecutando tu script. Ejecuta tu script para que lo constates.
PRINT "------ USING SHELL ------"
 
SHELL "ls -B -g"
Como de seguro ya notaste, puedes declarar todo tipo de variabes, incluso arrays; pero no esta limitado a esto, tambien puedes hacer uso de procedimientos, funciones y casi todos los recursos disponibles en el lenguaje Gambas.
Actually the output of this script is basically the same output that you obtain with the linux ls -g -B console command.
 
Execute the script with gbs2 ls.gbs and see what happen.
*'''Leer entradas por el usuario'''
As you already note in the previous examples, you can declare all type of variables, even arrays; but is not limited to that, you can make use of procedures, functions, and almost everything in Gambas Language.
Cuando un script esta siendo ejecutado, frecuentemente es necesario que reciba cierta retroalimentación del usuario para iniciar alguna tarea o para tomar alguna decision o cualquier otra cosa que deba hacer. Escribe el siguiente código en un archivo llamado ''preguntanombre.gbs''.
Reading User Input
#!/usr/bin/env gbs2
When a script is running, frequently is necessary to receive some feedback from the user to start some task or to make decisions or any other fancy thing you need to do. Write the following code on a file called askname.gbs.
INPUT DIM userInput AS String
#!/usr/bin/env gbs2
PRINT "Por favor, introduce tu nombre:"
'This script reads some text from the user and then print it
DIM INPUT userInput AS String
PRINT "Hey " & userInput &"! ThisRecibí istu an user inputrespuesta. CoolYupi!"
PRINT "Please enter your name:"
 
INPUT userInput
Ejecuta el script y veras que pregunta por tu nombre y despues que presiones [Enter] aparece un mensaje usando la cadena de caracteres que tecleaste.
PRINT "Hey " & userInput &"! This is an user input. Cool!"
user@PC:~$ gbs2 '''askname.gbs'''
Run the script, you’ll be prompted for your name and after press [Enter] the message using your name will appear on the screen.
PRINT " ''Please enter your name:" ''
user@PC:~$ gbs2 askname.gbs
'''Sergio'''
Please enter your name:
''Hey Sergio! This is an user input. Cool!''
Sergio
user@PC:~$
Hey Sergio! This is an user input. Cool!
 
user@PC:~$
Passing*'''Pasar argumentsargumentos to theal script'''
Algunas otras veces, desearas recibir la información del usuario desde un inicio como argumentos del script. Esto lo consigues haciendo uso del array ''Args[]'' de la clase ''Application''. Escribe el siguiente codigo en un archivo llamado ''argumentos.gbs''.
Some other times, you’ll want to receive some input from the user as arguments at the moment the user calls the script. You can do this, as you do with command-line applications, by accessing the Args[] array from the Application class. Write the following code and save it as arguments.gbs.
#!/usr/bin/env gbs2
PUBLIC SUB Main()
'This script displays the list of arguments passed
DIM i AS Integer
PUBLIC SUB Main()
DIM iarg AS IntegerString
'Using a FOR-NEXT loop
DIM arg AS String
FOR EACHi arg= IN0 TO Application.Args.Count
'Using a FOR-NEXT loop
FOR i = 0 TOPRINT Application.Args.Count[i]
NEXT
PRINT Application.Args[i]
'Using a FOR-NEXTEACH loop
NEXT
'Using a FOR- EACH looparg IN Application.Args
Print arg
FOR EACH arg IN Application.Args
Print argNEXT
'Using a FOR-NEXT loop
PRINT “\nThis loop starts from 1 not from 0”
'Using a FOR-NEXT loop
FOR PRINTi = 0 TO Application.Args[i].Count
PRINT “\nThis loop starts from 1 not from 0”
FOR i = 0 TOPRINT Application.Args.Count[i]
NEXT
PRINT Application.Args[i]
END
NEXT
Hasta el momento, los scripts que habias escrito empezabas sin ninguna declaración del método ''Main()'', pero ahora, para poder acceder a la clase ''Application''
END
So far now, all the scripts in this lesson started without any Main() method declaration, but in order to gain access to the Application class, you need to declare a startup method. Actually it is a good practice to always make use of the Main() method even for small scripts.
Run the script.
Línea 114:
DIM sEnv AS String
%>
< !-- Variable declaration must come before any HTML -- >
< html >
< h2 >CGI script environmental variables< /h2 >
< table border="1" cellspacing="0" cellpadding="2" >
< tr >
< th align="left">Name< /th >
< th align="left">Value< /th >
< /tr >
<% FOR EACH sEnv IN Application.Env %>
<tr valign="top">