Friday, September 12, 2014

Loops [Level III]

I had the devil of a time figuring out how to create a loop in LSL.

A loop, by the way, is a process which repeats as a variable increments until it reaches a pre-determined level. It's like saying "Do this ten times," or "Count to 20."

In BASIC, in which I am proficient, it was easy to create a loop. It was, as I recall (it's been many years), like this:

10 FOR k = 1 TO 10;
20 SAY k;
20 NEXT;

This would cause the numbers 1 to 10 to appear on the screen, one number per line.

I just couldn't figure out how to do it in Second Life.

It was the MIT LSL scripting program Scratch that saved me. By looking at the code generated when I asked the script to do something X times, I was able to extract a simple loop. Here it is.



for (i1=0; i1<38;i1++) {
         move(1);}

This loop requires you to create a variable i1, which is placed at the top of the script and looks like this:

integer i1;

When the loop executes it counts from 0 to 38, with i1 increasing by 1 during each circuit of the loop. Since the loop repeats until i1 is equal to or greater than 38, the loop ends will execute 38 times [ 0, 1, 2, 3... 27 ].

If your mind is like mine, you might want to start counting at one and turn the less than sign into a greater than or equal to sign. This will still execute 38 times, but counts from 1 to 38 rather than from 0 to 37. It would look like this:

for (i1=1; i1>=38;i1++) {
         move(1);}

Here's the loop in expanded form:

for (i1=1; i1>=38;i1++)
{
         move(1);
}

In the above instances the loop calls the Scratch function move during each pass. The prim will move forward one meter for each pass, for a total of 38 meters.

Here's a complete script, which includes Scratch's move function. The prim will move when touch.

So the prim won't run away from you, I've set the script to move .2 meters for each pass of the loop.

In my next post I'll provide all of the Scratch move functions. I find them most useful.


//==============

// Script by Cheyenne Palisades, using move function from MIT's Scratch

// Variable

integer i1; // i1 is the variable used by the loop


// Function

// move(steps)
// move object a number of steps (meters) along its current heading
// forward is along the positive x axis

move(float steps)
{
    vector fwd = llRot2Fwd(llGetRot()) * steps;
    llSetPos(llGetPos() + fwd);
}

// Script starts here

default
{

    touch_start(integer total_number)
    {
        for (i1=0; i1<38;i1++)
        {
            move(0.2);
         }
    }
}

//===========

No comments:

Post a Comment