Help:Getting started with LSL/es

From Second Life Wiki
Jump to navigation Jump to search

Primeros pasos en LSL de secuencias de comandos en Second Life

LSL significa "Linden Scripting Language" y se utiliza a la escritura los objetos que se encuentran y que en Second Life.

PARA QUIEN ES ESTE TUTORIAL:

Este tutorial está destinado a aquellos que nunca han programado antes, Second Life o en otro lugar. Sin embargo, este tutorial no tienen mucho sentido fuera de Second Life. LSL es muy específico a Second Life.

Usted comenzará a correr por la norma "hola mundo" secuencia de comandos y se aproxime a hacer el suyo propio. Usted tendrá que estar familiarizado con los principios básicos de Second Life y tener habilidades generales de creación de poder hacer uso de todo en este tutorial.

Que es LSL?

LSL es el Linden Scripting Language. Este es el lenguaje todos los scripts de Second Life se escriben pulg La estructura de la LSL se basa principalmente en Java y C, los cuales son ampliamente utilizados lenguajes de programación en el mundo real. Una secuencia de comandos en Second Life es un conjunto de instrucciones que se pueden colocar dentro de cualquier objeto primitivo del mundo, pero no dentro de un avatar. Avatares, sin embargo, puede usar objetos programados. LSL scripts están escritos con un editor incorporado / compilador que vamos a acceder en "Realización de la primera secuencia de comandos".

NOTA: LSL se interpreta y ejecuta en los servidores de Second Life (Sims), no el cliente (Visor). Aunque el editor de scripts es parte del Visor de SL, el propio script se ejecuta en el servidor, que envía los resultados a través de la red el visor, donde se puede ver.

Una cosa que hace LSL único es su énfasis en "los Estados" y "Eventos". Una puerta puede ser "abierto" o "cerrado" y una luz puede ser "en" o "apagado". Una persona puede ser "hiper", "calma" o "aburrido". Muchos comportamientos de la vida real puede ser modelado con "estados" y lo mismo puede decirse de los programas de LSL. Un guión mínimamente tendrá un estado, el estado por defecto.

Un evento puede ser considerado como un "Trigger". Los eventos no están definidos por el usuario en Second Life, pero en lugar predefinido. Ellos son causados por los objetos y avatares que interactúan en el mundo, o son creados en un script. Eventos gatillo controladores de eventos (algunas veces llamados "eventos" también). Por ejemplo, cuando uno toca un objeto avatar, un touch_start'mensaje se envía al objeto, que hace que el touch_start () del controlador de eventos para comenzar la ejecución. Así que el programa mínimo LSL debe tener un estado con un controlador de eventos en el mismo. He aquí un vistazo a un programa mínimo escrito en LSL que libremente se puede traducir como ...." Cuando estoy en el estado por defecto, y me tocó, por ejemplo "Hola Mundo" en el canal cero ".


<lsl> default {

    touch_start(integer total_number)
    {
         llSay(0,"Hello World");
    }

} </lsl>

¿QUE PUEDO HACER CON LOS SCRIPTS

Los scripts pueden hacer que un objeto se mueva, escuchar, hablar, actuar como un vehículo o arma, cambian de color, tamaño o forma. Un script puede hacer que un objeto escuchar sus palabras, así como hablar con usted, incluso scripts deje objetos se comuniquen entre sí.

El objeto más básicas en Second Life es el "Prim" o primitiva, el componente básico de todos los objetos que usted puede construir en Second Life. Cuando prims varias están vinculadas, que contienen cada uno un guión que habla con el resto del objeto a través de mensajes de Link. Estos son más rápidos y más privado de tener objetos "chat" o por correo electrónico unos a otros. Estos están fuera del alcance de este tutorial, sino sobre todo se centrará en las secuencias de comandos individuales en un solo prim.

Secuencias de comandos es más difícil de aprender que la manipulación de objetos básicos, pero es muy gratificante una vez que avanzar.

Si usted ha construido en Second Life, todo lo que puede definir en la ventana de edición se puede definir en un script. Toda la interacción entre los objetos que ves o entre los avatares y objetos es a través de scripts.

Aprender más sobre el mundo y modelo de construcción es de vital importancia a algunos aspectos de secuencias de comandos, con lo que yo recomendaría una buena base en la construcción a medida que aprende a la escritura.

Corriendo su primer Script

Tradicionalmente se comienza por escribir el programa más pequeño posible imprimir "hola mundo". Desde LSL sólo se ejecuta dentro de los objetos, debe saber cómo crear un objeto y poner un script dentro de él.

Usted debe estar en tierra que permite la construcción. Puede ser que su propia tierra, o la tierra donde usted tiene permiso para construir en como una caja de arena. Haga clic derecho sobre el terreno y elegircrear (para una macs utilice el botón de comando haga clic en +).

De forma predeterminada, deberá ver el iconola varita de un'con el que podrás seleccionar y crear un cubo en el suelo.

You will automatically enter edit mode and an edit window will pop up. To place a script in an existing object, right click it and hit edit to open the edit window.

In the edit window you may see a button marked more>>> click it to reveal five tabs marked general, object, features, content, and texture. Click content.

This window shows the contents of an object which can hold scripts, notecards, even other objects. Press new script to add a new script.

This will open the LSL editor with a default script. This editor will color code your syntax and provide some info about keywords when you hold your mouse over them. It will also do basic syntax checking.

Before explaining the code, lets run it. Hit save and close your edit window (not the LSL editor window).

You should see the words "Hello Avatar" from "object"

If you touch the object, it will say "Touched." The "edit" building window must be closed for touching to work.

Congratulations! You have compiled and run your first LSL script!

Development Cycle

(aka Wash / Rinse / Repeat)

We now have a running script, however most scripts you make will not run the first time you run them. It will take many tries as you correct errors and make improvements. When you hit "save" on a script, the LSL editor "compiles" the code to something LSL can understand. It will stop however if it finds an error.

Brackets, parenthesis, and semicolons must all be perfectly in place before a script will run. If you are new to programing this can be one of the most infuriating steps and lead you to screaming DWIM (Do what I mean!) Part of becoming a programmer in ANY language is learning how to precisely define steps and correctly type them into the language you are working in. Thus you will find yourself writing, running, then RE-writing your code several times.

The script you made runs the instant you hit save. If you take it into inventory, it will "suspend" what it was doing but go right back to it when rezzed (resurrected) again. (If you are not familiar with "taking" and "rezzing" an object you may need to revisit your building skills).

Each time you re-write your code, reset the script. Try resetting the script in the following ways:

  1. Press Reset in the script window.
  2. Select the object and choose TOOLS>RESET SCRIPTS IN SELECTION
  3. By checking and unchecking the "running" button
  4. Choose TOOLS>SET SCRIPTS TO NOT RUNNING IN SELECTION and then TOOLS>SET SCRIPTS TO RUNNING IN SELECTION.

Once you get comfortable with stopping, starting, and resetting a script, try changing the words "Hello Avatar" and see what else you can make it say.... for goodness sakes keep it PG.

WHY STOP AND START?

Scripting in Second Life can be a little bit like fixing your car...while going 60mph down the freeway. Thus you need ways to stop the programs for they may affect others.

Objects can hold more than one script and they will all run at once. This can be used in the following manner. Say you write a script that makes a prim change color every few seconds. You also write one to make it follow you. Put them both in one object and it will follow you while changing colors!

For simplicity's sake, the following examples will all be used individually so be sure not to put two or more into the same object.

Dissecting "Hello World"

Lets take a look at the default code.

<lsl> default {

    state_entry()
    {
        llSay(0, "Hello, Avatar!");
    }
    touch_start(integer total_number)
    {
        llSay(0, "Touched.");
    }

} </lsl>

The code above contains 1 state, 2 events and 2 functions. Lets look at them individually.

Any line starting with two forward slashes is a comment. It will not run and is used to help you document your code.

// This is a comment

STATES

A "State" in LSL is a section that is running, and waiting for events. Only one state can be active at any one time per script. Every script must have a default state with at least one event in it. Except for the default state, each state is defined by the word STATE followed by the name of the state. The contents of the state are enclosed in two curly brackets.

<lsl> default { // contents of state go here }

state playing { // this is a state called "playing" } </lsl>

EVENTS

Events are inside of states. By "inside" I mean it is between the open and closed curly brackets that represent the body of the state. When that state is active, those events wait to be triggered and run the code inside them. We have seen "state_entry" which is triggered by the state being entered, and "touch_start" which is triggered when you, or anyone, touches an object.

Lets take a look at the default code.

<lsl> // Code start default {

    touch_start(integer total_number)  // this is an event
    {
    // this is the content of the event (between curly braces)
    }

} // end of default state </lsl>

FUNCTIONS

Functions lay inside of events and are either defined by you or built-in. Those built in to LSL all start with two lowercase Ls. We have seen llSay() so far. Functions take "arguments" or values in the parentheses that follow it. If you hover over the function in the editor, a pop-up will show that tell you what the function is expecting. In the case of llSay it expects a number and a string. We send it the number zero and the string "Hello, Avatar!" separated by commas. The function is "expecting" a number and strings and will not take anything else.

Putting it all together

Line by line, here is the hello avatar script.

<lsl>

default // All Scripts need a Default State

{ // this open curly bracket denotes the start of the state

   state_entry() // an event
   {
       llSay(0, "Hello, Avatar!"); // a  function inside the event's curly braces
   }
   // closed curly bracket closes the state_entry event
   touch_start(integer total_number)  // another event inside default state
   {
       llSay(0, "Touched."); // a function between the brackets of the touch_start body
   }
   // end of touch start

} // Code end </lsl>

The instant you save your script, it enters default state, which in turn runs the "state_entry" event which in turn runs the function llSay() which makes the object talk.

After this, the program waits idle in the default state until a new event is called.

Touching the box triggers the event "touch_start" which also makes the object speak.

Introducing States and Events

LSL scripts will not run beginning to end. Instead, they will look for a default state and wait for an event. Within those events, there can be a call to go to a new state.

All programs must contain the default state, inside of which must be one event. Events are triggered either by actions happening to or around the object the script resides in, or are triggered from the script itself.

On/Off Example Using States

Let us look at a script with two states with two events in each.

<lsl> default //default state is mandatory {

   state_entry() // runs each time the state is entered
   {
       llSay(0, "turning on!"); //object speaks!
       llSetColor(<1.0, 1.0, 1.0>, ALL_SIDES); // sets all sides to most bright
       // note the semicolons at the end of each instruction (do not put them at the end of if statements)
   }
 
   touch_start(integer total_number) // another event with only one function  inside
   {
       state off; // sets the script to a new "state" and starts running "state off"
   }

} // this curly bracket ends the body of the default state.

state off // a second state besides "default" {

   state_entry() // this is run as soon as the state is entered
   {
       llSay(0, "turning off!");
       llSetColor(<0.0, 0.0, 0.0>, ALL_SIDES); // sets all sides as dark as possible
   }

   touch_start(integer total_number)
   {
       state default;
   }

} </lsl> A simplification of this would be


<lsl>

default
{
//set color to light and, if touched, enter the "off" state.
}

state off
{
//set color to dark and, if touched, enter the "default" state.
}

</lsl>

Note that after "default" all new states begin with the word "state". Also, while the object has a texture, the color will affect the "tint" more than the true color.

Default State

Let us examine the default state.

First we see the "state_entry" event, which gets triggered each time the default state is entered. Which is this case in entered the first time the script is run.

SPEAK TO ME!

The first line in the event state_entry is...

<lsl>llSay(0, "turning on!");</lsl>

This makes the object speak "turning on!" on channel zero. What is channel zero? It is the same channel you see all public chat on.

A semicolon ends the line and yet another instruction follows.

<lsl>llSetColor(<1.0, 1.0, 1.0>, ALL_SIDES);</lsl>

This turns the prim to its brightest tint. If you take the texture off the prim, you would see it as bright white but with a texture, it looks "normal." The three ones stand for the Red, Green, and Blue values of the tint.

At this point the event is finished with the two lines of commands. Then the script waits idle in the default state for more events to happen.

TOUCHED BY AN AVATAR

While idle in the default state a touch will trigger the "touch_start" event.

Inside of the "touch_start" event is only one command:

<lsl>state off;</lsl>

This is a command to move immediately to a new state named "off".

This state is defined after the default state and nearly mirrors the default state, except that it turns the prim dark and, when touched, will put the script back into default mode, thus creating a loop.

  1. Enters default state
  2. Runs code in "state entry"
  3. Waits to be touched
  4. When touched enters "state off"
  5. Enters "state off"
  6. Runs code in "state entry" (note in the "off" state's body)
  7. Waits to be touched
  8. When touched enters "default" state

Then the whole thing starts over.

A final word on words

Making your object speak is a great way to know what a script is doing, but everyone can hear it for 20m all around you. As you get into more complex scripts this can get pretty noisy! Three alternative ways to see what is going on exist.

SHHHH WHISPER

llWhisper( ) is just like llSay( ) but only broadcasts at half the distance (10m). You still must state what channel. So...

<lsl>llWhisper(0,"turning on!");</lsl>

...might work a bit to save the sanity of your neighbors.

Using llShout( ) increases the distance heard to a radius of 100m, but can cut the amount of friends you have in half.

llOwnerSay( ) uses no channel and is heard only by the owner of the object. Very useful and can triple the amount of friends you have!

<lsl>llOwnerSay("turning on!");</lsl>


THE SOUND OF SILENCE

You can make a totally silent message via llSetText( ) like this.

<lsl>llSetText("I am on", <1.0, 1.0, 1.0>,1.0);</lsl>

What do the numbers mean? The <1.0, 1.0, 1.0> we have seen before. It represents the values for red, green, and blue. For now just know that <1.0, 1.0, 1.0> means "white" and <0.0, 0.0, 0.0> means "black". Replace the llSay(0,"turning off!"); with...

<lsl>llSetText("I am off", <0.0, 0.0, 0.0>,1.0);</lsl>

The 1.0 is the alpha setting. 1.0 means fully opaque, and 0.0 would be completely transparent (invisible).


Next steps

Now than you can edit and run LSL code, move on to one of the more advanced LSL Tutorials.