Difference between revisions of "Getting started with LSL/it"

From Second Life Wiki
Jump to navigation Jump to search
(New page: {{Help}} {{LSL Header}} == Incominciamo a scriptare con il linguaggio LSL in Second Life == LSL sta per "Linden Scripting Language" ed è usato per programmare gli oggetti che incontrere...)
 
Line 4: Line 4:
== Incominciamo a scriptare con il linguaggio LSL in Second Life ==
== Incominciamo a scriptare con il linguaggio LSL in Second Life ==


LSL sta per "Linden Scripting Language" ed è usato per programmare gli oggetti che incontrerete e che farete in SecondLife.
LSL sta per "Linden Scripting Language" (Linguaggio di Programmazione Linden) ed è usato per programmare gli oggetti che incontrerete e che farete in SecondLife.


WORK IN PROGRESS!!!!!!


'''A CHI E' RIVOSTO QUESTO TUTORIAL:'''


'''FOR WHOM IS THIS TUTORIAL:'''
Questo tutorial è pensato per coloro che non hanno mai programmato prima, in Second Life o da altre parti. Questo tutorial ha molto poco senso al di fuori di Second Life.  LSL è molto specifico per Second Life.


This tutorial is intended for those who have never programmed before, Second Life or elsewhere. However, this tutorial will make little sense outside of Second Life.  LSL is very specific to Second Life.
Comincerai facendo girare il programmino standard "ciao mondo" ed alla fine riuscirai a produrne uno scritto di tuo pugno. Devi però conoscere i principi base di Second Life e possedere le conoscenze di build di base prima di poter utilizzare a pieno questo tutorial.


You will begin by running the standard "hello world" script and eventually move towards making your own.  You will need to be familiar with the basic principles of Second Life and have general building skills before you can make use of everything in this tutorial.
== Cos'è il linguaggio LSL? ==


== What is LSL? ==
LSL è il linguaggio di programmazione (scripting) Linden. Questo è il linguaggio con cui sono scritti tutti gli script in SecondLife. La struttura è basata su Java e C. Uno script in Second Life è un insieme di istruzini che possono essere messi dentro un prim, ma non dentro un avatar. Gli Avatar possono indossare oggetti scriptati. Gli script LSL sono scritti usando un editor/compilatore precostruito nel vostro viewer che vedremo nel capitolo "Come lanciare il tuo primo script".


LSL is the Linden Scripting Language. This is the language all scripts in Second Life are written in. Its structure is based on Java and C. A script in Second Life is a set of instructions that can be placed inside any primitive object in the world, but not inside an avatar. Avatars, however, can wear scripted objects.  LSL scripts are written with a built-in editor/compiler which we will access in "Running Your First Script".
NOTA: LSL è interpretato ed eseguito nei server di Second Life servers (chiamati sim), non nel client (Viewer). Sebbene l'editor degli script sia parte del viewer, lo script risiede nel server, che manda i risultati sulla rete al Viewer, dove alla fine li osservi.


NOTE: LSL is interpreted and executed on the Second Life servers (sims), not the client (Viewer). Although the script editor is part of the SL Viewer, the script itself runs on the server, which sends the results over the network to the Viewer, where you can see them.
Una cosa che rende il linguaggio LSL "speciale" è la sua enfasi sugli "Stati" e sugli "Eventi". Una porta può essere "aperta" o "chiusa" e una lampadina può essere "accesa" o "spenta". Una persona può essere "eccitata", "calma", o "annoiata". Molti comportamenti della nostra vita reale possono essere modellati attraverso degli "stati" e lo stesso vale per i programmi LSL. Uno script avrà come minimo uno stato, lo stato di "default" (o stato iniziale).


One thing that makes LSL special is its emphasis on "States" and "Events". A door can be "open" or "closed" and a light can be "on" or "off". A person can be "hyper", "calm", or "bored". Many real life behaviors can be modeled with "states" and the same can be true for LSL programs. Minimally a script will have one state, the default state.
Un evento può essere pensato come un "Grilletto" o "Interruttore" qualcosa che scatta in certe condizioni predefinite. Gli Eventi non sono definibili dagli utenti in SecondLife, ma sono predefiniti. Sono fatti scattare quando gli oggetti o gli avatar interagiscono con il mondo, oppure possono essere scatenati esplicitamente dentro uno script. Gli eventi fanno scattare i gestori degli eventi (che vengono chiamati a loro volta "eventi"). Per esempio, quando un avatar tocca un oggetto, un messaggio ''touch_start'' è inviato all'oggetto, il che mette in esecuzione il gestore di eventi [[touch_start]]() che inizia a girareIl programma minimale LSL deve avere '''uno''' stato e '''un''' gestore eventi. Ecco come appare un programma minimale scritto in LSL che a grandi linee può essere tradotto come.... "Quando sono nello stato iniziale e sono toccato, dico "Ciao Mondo" sul canale 0".
 
An event can be thought of as a "Trigger".  Events are not user defined in Second Life, but rather predefined. They are either caused by objects and avatars interacting in the world, or they are created in a script. Events trigger event handlers (sometimes just called "events" as well). For example, when an avatar touches an object, a ''touch_start'' message is sent to the object, which causes the [[touch_start]]() event handler to begin executingSo the minimum LSL program must have one state with one event handler in it. Here is a look at a minimal program written in LSL that can loosely be translated as...."When I am in the default state, and I am touched, say "Hello World" on channel zero".




Line 31: Line 29:
     touch_start(integer total_number)
     touch_start(integer total_number)
     {
     {
           llSay(0,"Hello World");
           llSay(0,"Cial Mondo");
     }
     }
}
}
</lsl>
</lsl>


'''WHAT CAN I DO WITH SCRIPTS?'''
'''COSA POSSO FARE CON GLI SCRIPT?'''
 
Gli script possono far sì che un oggetto si muova, ascolti, parli, funzioni come veicolo oppure come un'arma, cambi colore, dimensione o forma. Uno script può fare sì che un oggetto ascolti le tue parole e te le ripeta a pappagallo, ci sono degli script che fanno parlare addirittura gli oggetti uno con l'altro.


Scripts can make an object move, listen, talk, operate as a vehicle or weapon, change color, size or shape. A script can make an object listen to your words as well as talk back to you, scripts even let objects talk to each other.
L'oggetto più fondamentale in Second Life è il Prim (il cubo), il blocco basilare per costruire tutti gli oggetti costruibili nel mondo virtuale. Quando tanti prim sono collegati (linkati), ognuno di essi può contenere uno script che può parlare con tutti gli altri prim attraverso dei "messaggi link" (linked message). Questi sono più veloci e più privati rispetto agli oggetti che "parlano" nei canali pubblici o si inviano email. Queste comunicazioni sono oltre l'intento di questo tutorial mentre invece ci concentreremo sugli script contenuti in un unico cubo.


The most basic object in Second Life is the "Prim" or primitive, the basic building block of all objects you can build in Second Life. When several prims are linked, they can each contain a script which speaks to the rest of the object via Link Messages. These are faster and more private than having objects "chat" or email each other. These are beyond the scope of this tutorial and we will instead focus on single scripts in a single prim.
Scriptare è più difficile che imparare la manipolazione di base degli oggetti, ma è veramente gratificante non appena fate qualche progresso.


Scripting is harder to learn than basic object manipulation, but is very rewarding once you make progress.
Se hai già costruito in Second Life, sappi che tutto quello che definisci nella finestra di edit può anche essere pilotato dagli script. Tutte le interazioni che vedi fra gli oggetti o tra avatar e oggetti avviene attraverso gli script.


If you have built in Second Life, everything you can define in the edit window can be defined in a script. All interaction you see between objects or between avatars and objects is via scripts.
Imparare di più sul mondo 3D e sul modello di building è vitale per alcuni aspetti dello scripting, per questo è raccomandabile avere delle cognizioni di base di building prima di imparare a scriptare.


Learning more about the world and building model is vital to some aspects of scripting, thus I would recommend a good foundation in building as you learn to script.
== Lancia il tuo primo script ==


== Running Your First Script ==
Tradizionalmente si comincia sempre scrivendo il più piccolo programma possibile che scriva "Ciao Mondo". Dato che LSL gira solo all'interno di oggetti, devi conoscere come creare un oggetto e come metterci dentro uno script.


Traditionally one starts by writing the smallest program possible to print "hello world". Since LSL only runs inside objects, you must know how to create an object and put a script inside it.
Devi essere in una terra che consenta il building. Può essere una tua terra, oppure una terra dove ti viene concesso di costruire come ad esempio una sandbox. Clicca con il tasto destro del mouse per terra e scegli '''create''' (se hai il mouse con un solo bottone del Mac devi cliccare command+click).


You must be on land which allows building. Either your own land, or land where you have permission to build on such as a sandbox. Right click on the ground and choose '''create''' (for one button macs use command+click).
Di default, dovresti vedere una icona a forma di '''bacchetta''' cliccando con questa icona per terra dovresti vedere creato un cubo ai tuoi piedi.


By default, you should see a '''wand''' icon with which you can click and create a cube on the ground.
WORK IN PROGRESS


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.
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.

Revision as of 12:29, 21 June 2009


Incominciamo a scriptare con il linguaggio LSL in Second Life

LSL sta per "Linden Scripting Language" (Linguaggio di Programmazione Linden) ed è usato per programmare gli oggetti che incontrerete e che farete in SecondLife.


A CHI E' RIVOSTO QUESTO TUTORIAL:

Questo tutorial è pensato per coloro che non hanno mai programmato prima, in Second Life o da altre parti. Questo tutorial ha molto poco senso al di fuori di Second Life. LSL è molto specifico per Second Life.

Comincerai facendo girare il programmino standard "ciao mondo" ed alla fine riuscirai a produrne uno scritto di tuo pugno. Devi però conoscere i principi base di Second Life e possedere le conoscenze di build di base prima di poter utilizzare a pieno questo tutorial.

Cos'è il linguaggio LSL?

LSL è il linguaggio di programmazione (scripting) Linden. Questo è il linguaggio con cui sono scritti tutti gli script in SecondLife. La struttura è basata su Java e C. Uno script in Second Life è un insieme di istruzini che possono essere messi dentro un prim, ma non dentro un avatar. Gli Avatar possono indossare oggetti scriptati. Gli script LSL sono scritti usando un editor/compilatore precostruito nel vostro viewer che vedremo nel capitolo "Come lanciare il tuo primo script".

NOTA: LSL è interpretato ed eseguito nei server di Second Life servers (chiamati sim), non nel client (Viewer). Sebbene l'editor degli script sia parte del viewer, lo script risiede nel server, che manda i risultati sulla rete al Viewer, dove alla fine li osservi.

Una cosa che rende il linguaggio LSL "speciale" è la sua enfasi sugli "Stati" e sugli "Eventi". Una porta può essere "aperta" o "chiusa" e una lampadina può essere "accesa" o "spenta". Una persona può essere "eccitata", "calma", o "annoiata". Molti comportamenti della nostra vita reale possono essere modellati attraverso degli "stati" e lo stesso vale per i programmi LSL. Uno script avrà come minimo uno stato, lo stato di "default" (o stato iniziale).

Un evento può essere pensato come un "Grilletto" o "Interruttore" qualcosa che scatta in certe condizioni predefinite. Gli Eventi non sono definibili dagli utenti in SecondLife, ma sono predefiniti. Sono fatti scattare quando gli oggetti o gli avatar interagiscono con il mondo, oppure possono essere scatenati esplicitamente dentro uno script. Gli eventi fanno scattare i gestori degli eventi (che vengono chiamati a loro volta "eventi"). Per esempio, quando un avatar tocca un oggetto, un messaggio touch_start è inviato all'oggetto, il che mette in esecuzione il gestore di eventi touch_start() che inizia a girare. Il programma minimale LSL deve avere uno stato e un gestore eventi. Ecco come appare un programma minimale scritto in LSL che a grandi linee può essere tradotto come.... "Quando sono nello stato iniziale e sono toccato, dico "Ciao Mondo" sul canale 0".


<lsl> default {

    touch_start(integer total_number)
    {
         llSay(0,"Cial Mondo");
    }

} </lsl>

COSA POSSO FARE CON GLI SCRIPT?

Gli script possono far sì che un oggetto si muova, ascolti, parli, funzioni come veicolo oppure come un'arma, cambi colore, dimensione o forma. Uno script può fare sì che un oggetto ascolti le tue parole e te le ripeta a pappagallo, ci sono degli script che fanno parlare addirittura gli oggetti uno con l'altro.

L'oggetto più fondamentale in Second Life è il Prim (il cubo), il blocco basilare per costruire tutti gli oggetti costruibili nel mondo virtuale. Quando tanti prim sono collegati (linkati), ognuno di essi può contenere uno script che può parlare con tutti gli altri prim attraverso dei "messaggi link" (linked message). Questi sono più veloci e più privati rispetto agli oggetti che "parlano" nei canali pubblici o si inviano email. Queste comunicazioni sono oltre l'intento di questo tutorial mentre invece ci concentreremo sugli script contenuti in un unico cubo.

Scriptare è più difficile che imparare la manipolazione di base degli oggetti, ma è veramente gratificante non appena fate qualche progresso.

Se hai già costruito in Second Life, sappi che tutto quello che definisci nella finestra di edit può anche essere pilotato dagli script. Tutte le interazioni che vedi fra gli oggetti o tra avatar e oggetti avviene attraverso gli script.

Imparare di più sul mondo 3D e sul modello di building è vitale per alcuni aspetti dello scripting, per questo è raccomandabile avere delle cognizioni di base di building prima di imparare a scriptare.

Lancia il tuo primo script

Tradizionalmente si comincia sempre scrivendo il più piccolo programma possibile che scriva "Ciao Mondo". Dato che LSL gira solo all'interno di oggetti, devi conoscere come creare un oggetto e come metterci dentro uno script.

Devi essere in una terra che consenta il building. Può essere una tua terra, oppure una terra dove ti viene concesso di costruire come ad esempio una sandbox. Clicca con il tasto destro del mouse per terra e scegli create (se hai il mouse con un solo bottone del Mac devi cliccare command+click).

Di default, dovresti vedere una icona a forma di bacchetta cliccando con questa icona per terra dovresti vedere creato un cubo ai tuoi piedi.

WORK IN PROGRESS

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.