User-defined functions

From Second Life Wiki
Jump to: navigation, search
Deletion Requested
The deletion of this article was requested for the following reason:

Content has been folded into Category:LSL_User-Defined_Functions

If there is a need to discuss the deletion of this article, please add your comment(s) here.


For a list of sample user-defined functions, go to Category:LSL_User-Defined_Functions

LSL allows user-defined functions. The syntax is very simple:

<lsl>

return_type variable_name(par1type par1name, par2type par2name,...)

 {
   function_statements;
   .
   .
   .
   return value_of_return_type;
 }

</lsl>

There are no "function" or "def" keywords or function type/inheritance specifiers needed. I have not yet discovered what limits (if any) exist on the length or composition of the parameter list. Multiple types can be used, as shown in the example below. A list can be returned, so a single function can return a list with several values in it. User-defined functions will help keep scripts compact and readable, and allow rudimentary code reuse. The LSL_Style_Guide suggests that user-defined functions should be placed before the default state definition and after user-defined variables. Placing user-defined functions after the first state will result in a Syntax Error.

Here are a couple of simple examples:

<lsl>

float xsquared(float x) // return the square of the argument {

   return x*x;

}

vector scalarmult(vector vIn, float sMult) // return the product of a scalar and a vector {

   vIn.x=vIn.x*sMult;
   vIn.y=vIn.y*sMult;
   vIn.z=vIn.z*sMult;
   return vIn;

}


default {

   state_entry()
   {
       llWhisper(0, "Some user functions");
   }
   touch_start(integer total_number)
   {
       float testx=3;
       llWhisper(0,"testx squared :"+(string)xsquared(testx));
       vector testVector = <1,2,3>;
       testVector = scalarmult(testVector,testx);
       llWhisper(0,"test vector is:"+(string)testVector);
   }

}


</lsl>