Page 1 of 1 1
Topic Options
#82017 - 03/03/15 09:11 PM How to write a UDF
Sealeopard Moderator Offline
KiX Master
*****

Registered: 01/04/25
Posts: 11161
Loc: Boston, MA, USA

==========================================
Part I: Why User-Defined Functions (UDFs)?
==========================================
Why do you want to write a UDF?
Most scripts contain actions that are performed multiple times. Just think of mapping 5 shares to drive letters. You end up having five sections that delete the potentially existing old drive mapping, create the new drive mapping, check for errors, and print out error/success messages. By using a UDF you encapsulate these steps in to a function/endfunction segment and pass information into the function as parameters just like you'd do with regular KiXtart functions. You now have a UDF.
Once you have this UDF, you can call it from anywhere in your script. You can also create a separate file containing UDFs as a library. You initialize this library at the beginning of your script and you now have a whole collection of UDFs availabe to you. The Kixtart.org UDF Forum already contains over 300 UDFs performing a wide range of tasks.
Another advantage of this UDF collection is that you can use them in different scripts by just including your library. You can easily share these functions with other script-writers and standardize your scripts based on these functions.
The next part will illustrate a standardized UDF format based on best practices collected from different UDF authors. It gives a good introduction in how to write a UDF that is easy to understand, portable, and emulates native KiXtart functionality pretty well.


Edited by kdyer (04/02/09 04:47 PM)
_________________________
There are two types of vessels, submarines and targets.

Top
#82018 - 03/03/15 09:11 PM Re: How to write a UDF
Sealeopard Moderator Offline
KiX Master
*****

Registered: 01/04/25
Posts: 11161
Loc: Boston, MA, USA


===============================
Part II: Recommended UDF Format
===============================

This part will illustrate a standardized UDF format based on best practices collected from different UDF authors. It gives a good introduction in how to write a UDF that is easy to understand, portable, and emulates native KiXtart functionality pretty well.
The following recommended UDF format is based on the most restrictive settings in KiXtart in order to make the UDF as universal as possible. End-users should not have to worry about their script settings in order to run this UDF. The most restrictive settings are

Code:

SETOPTION('Explicit','On')
SETOPTION('NoVarsInStrings','On')
SETOPTION('CaseSensitivity','On')



EXPLICIT: This option requires to DIM all variables used in your UDF, they will thus not conflict with any variable of the same name that has been created outside the UDF.
NOVARSINSTRINGS: This option requires to not use variables within string delimiters.
CASESENSITIVITY: This option requires to compare strings by explicitly converting them to LCASE or UCASE if you do not want case sensitivity to be a deciding factor


Input Variables Your code should also check input variables for correct format and content. This will ensure that only correct paarameters are used iside your code. Incorrect values might have unexpected side-effects.
Error Codes When exiting a function in case of errrors, set an appropriate error code with EXIT. Windows error codes can be found under Microsoft Windows SDK: System Error Codes.
The Header
Fill out all header sections with meaningful and explanatory content. This makes it easier for KiXtart novices to understand the UDF and what parameters it needs to accomplish it's function.

Dependencies
A UDF does not need to check for the existance of its dependencies. However, dependencies must be noted in the UDF header. Also, the UDF does not need to check for the correct KiXtart version. Missing dependencies and incorrect KiXtart versions will already lead to error messages on the command prompt when running the script.

External Utilities
If a UDF is dependent on the presence of other components that might not be present o a computer, then this should be noted in either the DEPENDENCIES or REMARKS section, but preferably the first one. Third-party utilities should be referenced including a source where it is available. For example, Windows 9x/NT do not necessarily have the Windows Management Interface (WMI) or the Active Directory Service Interface (ADSI) installed. Thus you will note the dependency on WMI and preferable reference a URL where to download the WMI component.

In general, KiXtart UDF strive to emulate the format of native KiXtart functions, both in functionality (e.g. setting of error codes) and documentation. This ensures consistency across different UDF writes with their diverse backgrounds.

At first, all these guidelines and best practices might seem like overkill to you. However, the UDF Library so far contains over 300 UDF and it is still growing. Extensive documentation also makes it easier to maintain UDFs across different releses of KiXtart.


Edited by kdyer (04/02/09 04:59 PM)
_________________________
There are two types of vessels, submarines and targets.

Top
#82019 - 03/03/15 09:11 PM Re: How to write a UDF
Sealeopard Moderator Offline
KiX Master
*****

Registered: 01/04/25
Posts: 11161
Loc: Boston, MA, USA


=====================================================
Part III: Example based on the Recommended UDF Format
=====================================================


Below is an example UDF illustrating the concepts mentioned in Part II. Please study it carefully!
Code:

dim $rc, $a, $b, $c, $d
$rc=SETOPTION('Explicit','On')
$rc=SETOPTION('NoVarsInStrings','On')
$rc=SETOPTION('CaseSensitivity','On')
$a='test'
$b=10
$c='whatever'
$d=11
$rc=UDFTemplate($a,$b,$c,$d)
? 'Error = '+@ERROR+' - '+@SERROR
? 'Result of UDFTemplate:'
? $rc

;FUNCTION UDFTemplateDemo()
;
;ACTION Illustrates best-practices concepts to be used in UDFs
;
;AUTHOR Jens Meyer (sealeopard@usa.net)
;
;CONTRIBUTORS Richard Howarth
;
;VERSION 1.0
;
;DATE CREATED 2003/03/15
;
;DATE MODIFIED 2003/03/17
;
;
;KIXTART KiXtart 4.20
;
;SYNTAX UDFTEMPLATEDEMO(VAR1, VAR2 [, VAR3, VAR4])
;
;PARAMETERS VAR1
; Required string parameter
;
; VAR2
; Required integer parameter
;
; VAR3
; Optional string paarmeter
;
; VAR4
; Optional integer parameter with bit-wise settings:
; 1 - 'Bit 1 is set'
; 2 - 'Bit 2 is set'
; 4 - 'Bit 4 is set'
; 8 - 'Bit 8 is set'
; 16 - 'Bit 16 is set'
;
;RETURNS String containing words
;
;REMARKS Please study carefully the concepts used
;
;DEPENDENCIES none (actually, a brain)
;
;EXAMPLE dim $rc, $a, $b, $c, $d
; SETOPTION('Explicit','On')
; SETOPTION('NoVarsInStrings','On')
; SETOPTION('CaseSensitivity','On')
; $a='test'
; $b=10
; $c='whatever'
; $d=11
; $rc=UDFTemplateDemo($a,$b,$c,$d)
; ? 'Error = '+@ERROR+' - '+@SERROR
; ? 'Result of UDFTemplate:'
; ? $rc
;
;KIXTART BBS http://www.kixtart.org/cgi-bin/ultimatebb.cgi?ubb=get_topic;f=12;t=000000
;
function UDFTemplateDemo($var1, $var2, optional $var3, optional $var4)
; DIM all variables used inside the UDF
dim $helpvar, $helparray[4]

; set the default return value
$udftemplate=''

; perform checks on all input parameters to make sure they fit the requirements
; if necessary, exit the UDF and return an error code

; var1 must be a string, thus convert to string if it is not a string
if vartype($var1)<>8
$var1=''+$var1
endif

; var 2 must be an integer, thus convert var2 into an integer
$var2=val($var2)

; var3 must be a string, thus convert to string if it is not a string
; however, it is also an optional parameter, thus we set it to a default value
; if the parameter is not provided
if vartype($var3)
if vartype($var3)<>8
$var3=''+$var3
endif
else
; parameter has not been provided, thus set default value
$var3='default value'
endif

; var 4 must be an integer, if it is provided
if vartype($var4)
if vartype($var4)<>2 and vartype($var4)<>3
; variable is not an integer, thus exit with 'Invalid Parameter' error code
exit 87
endif
else
; parameter has not been provided, thus set default value
$var4=0
endif

? 'Content of variable $var1 = '+$var1
? 'Variable type of $var2 = '+vartype($var2)+' - '+vartypename($var2)
? 'Content of variable $var3 = '+$var3

; demonstrating bit-wise decisions
for $helpvar=0 to 4
if $var4 & ($helpvar+1)
$helparray[$helpvar]='Bit '+($helpvar+1)+' is set'
else
$helparray[$helpvar]='Bit '+($helpvar+1)+' is not set'
endif
next

$udftemplate=join($helparray,@CRLF)

; UDF ran successfully, thus set exit code to 0
; this is optional, however it will reset a potentially
; existing @ERROR back to 0
exit 0
endfunction




Edited by kdyer (04/02/09 04:51 PM)
_________________________
There are two types of vessels, submarines and targets.

Top
#82020 - 03/03/15 09:12 PM Re: How to write a UDF
Sealeopard Moderator Offline
KiX Master
*****

Registered: 01/04/25
Posts: 11161
Loc: Boston, MA, USA


=====================
Part IV: UDF Template
=====================

Below is an empty UDF to be used as a template

Code:

;FUNCTION Name_of_UDF
;
;ACTION Short description of purpose
;
;AUTHOR Name of author
;
;CONTRIBUTORS Name(s) of contributor(s)
;
;VERSION UDF version
;
;DATE CREATED YYYY/MM/DD
;
;DATE MODIFIED YYYY/MM/DD
;
;KIXTART Minimum required Kixtart version
;
;SYNTAX NAME_OF_UDF(PARAMETER 1, PARAMETER2 [, PARAMETER3])
;
;PARAMETERS PARAMETER1
; Description of first parameter
;
; PARAMETER2
; Description of second parameter
;
; PARAMETER3
; Description of optional first parameter
;
;RETURNS Type of return value
;
;REMARKS Additional remarks about the UDF
;
;DEPENDENCIES DependUDF @ http://www.kixtart.org/board/...
; Name and URL of UDFs that this UDF depends on
;
;EXAMPLE A short functional example demonstrating the UDF
;
;KIXTART BBS http://www.kixtart.org/cgi-bin/ultimatebb.cgi?ubb=get_topic;f=12;t=000000
; URL the UDF was posted under
;
function Name_of_UDF($parameter 1, $parameter2, optional $parameter3)
endfunction




Edited by kdyer (04/02/09 05:01 PM)
_________________________
There are two types of vessels, submarines and targets.

Top
#82021 - 03/03/15 09:12 PM Re: How to write a UDF
Sealeopard Moderator Offline
KiX Master
*****

Registered: 01/04/25
Posts: 11161
Loc: Boston, MA, USA


========================================
Part V: Implementing UDFs into your code
========================================

The following section was provided by Richard Howarth and was originally posted under GOSUB vs. FUNCTIONAn example might help.
Say you write an application that uses a database to store records. You want the very basic facilities like add a record, delete a record, find a record, list all records.
You could write these as subroutines in your application but there are two problems with that.
? 1) The code may be useful in other applications - using subroutines means that you need to cut and past the code - a big overhead in script size and maintenance.
? 2) You have to pass variables to/from the subroutine using global variables. This means that to use the subroutines you have to know what the variables are called, and your subroutine is in danger of overwriting variables that you are using in the main script.
You can solve "1" by simply putting each of your subroutines in a file on it's own, and CALLing the file. This will execute the script in the file as if it was in your main script. For example, you would place your add record routine in a file called "AddRecord.kix", and when you want to add a record you use the script command
Code:

CALL "AddRecord.kix"


In this case your variables may be local, but you still need to know what they are, and you still need to be careful about overwriting variable in the main script.
Also there is the overhead of reading and parsing the file every time you make the CALL.
So, we come to the best all round option - libraries of functions.
Functions can be designed as black-boxes in almost all cases - there are a couple of exceptions which I'll note later.
The benefit of this is that you only ever have to know the function name and expected parameters. You don't need to know how it works, and you don't need to know what it is using as variables internally.
An additional but often overlooked benefit of functions is that you can set @ERROR on exiting the function. You use this in your main script to determine whether the function call worked or not.
For your database routines, you create a file called "SQLroutines.kix". In this file you create all of your functions:
Code:

Function fnAddRecord($sKey,$asRecord)
;... Add Record Code ...
$fnAddRecord=$iSuccess
Exit $iSuccess
EndFunction
Function fnDeleteRecord($sKey)
;... Delete Record Code ...
$fnDeleteRecord=$iSuccess
Exit $iSuccess
EndFunction
Function fnFindRecord($sSearchString)
;... Find Record Code ...
$fnFindRecord=$sKey
Exit $iSuccess
EndFunction
Function fnGetRecord($sKey)
;... Get Record Cose ...
$fnGetRecord=$asData
Exit $iSuccess
EndFunction
;and so-on ...


To use these functions you call the script file once at the start of the script. This has the effect of loading the functions into memory, where they will stay until you exit your main script. You can now call the functions as often as you like, without the overhead of reading and parsing the script file.

You call the function in the same way as internal KiXtart functions, so the following are all valid:
Code:

$UserLogin='jdoe'
$UserData[0]='John'
$UserData[1]='Doe'
$UserData[2]='Trainee Clown'
If fnAddRecord($UserLogin,$UserData)
? 'ERROR: Could not add record for '+$UserLogin
? ''+@ERROR+': '+@SERROR
Else
? 'Record added OK.'
EndIf
If fnDelRecord('jdoe')
? 'ERROR: Could not delete record'
EndIf
$UserLogin=fnFindRecord('Clown')
If @ERROR
? "No clowns in this organisation."
Else
$UserData=fnGetRecord($UserLogin)
If @ERROR
? 'ERRROR: Invalid key '+$UserData
Else
? $UserData[1]+' '+$UserData[2]+' is a clown.'
EndIf
EndIf


Neat, huh?

For advanced usage the library method has another major advantage.

Say you want to deploy your database applications to many sites. Some are very small sites which use flat text files for storing data, some are medium sized sites which use Access for storing data and some are large sites which use LDAP or SQL for storing data.

Now you could write applications for each, but wouldn't it be easier to do something like this at the start of your script:
Code:

$DATABASETYPE=fnGetDBType()
Select
Case $DATABASETYPE='TXT'
CALL 'TXTroutines.kix'
Case $DATABASETYPE='SQL'
CALL 'SQLroutines.kix'
Case $DATABASETYPE='ODBC'
CALL 'ODBCroutines.kix'
Case $DATABASETTYPE='LDAP'
CALL 'LDAProutines.kix'
EndSelect


or more simply:
Code:

CALL fnGetDBType + 'routines.kix'


Each of these files will have a "fnAddRecord()" defined. Your script doesn't need to know which database method is being used when you add a record. The correct version will have been loaded by the "CALL" at the starte of your script.

You may remember that I mentioned that there are some cases when you cannot make a routine in a "black-box" fashion.

The first problem is when you want to keep some information and re-use it in your function. These types of variables are known as "static" variables in some languages.
For example, you may only want to set up a connection to your database once as it is an expensive thing to do in computer terms. At present the only way to keep this information between function calls is to define it in a GLOBAL variable. This variable will have the scope of your entire script, so can clash with your main script variables.

The other problem area is when you want to change the value of one of the parameters. A simple classic example is the "POP" routine. This takes a stack, "pops" the top element off the stack and returns the popped off element. Consider a function to "pop" off the first character in a string:
Code:

Function fnPopString($sString)
If $sString=''
Exit 1
EndIf
$fnPopString=Left($sString,1)
$sString=SubStr($sString,2)
Exit 0
EndFunction


Looks good, eh?

Well no, it won't work. The variable $sString is LOCAL to the function, and is destroyed on exit. It is a copy of the string that you passed in your main script. Passing this type of information is known as "passing by value"

For functions which need to change variables outside their scope you need to use a method known as "pass by reference", or "pass by address". This method passes a pointer to the original variable so that it can be manipulated in the function.

KiXtart does not currently support pass by reference, so again you will need to use GLOBAL variables to achieve the result.

There is an advanced coding technique which you can use to abstract the variable name, but the variable you want to change still must be global.


Edited by kdyer (04/02/09 05:05 PM)
_________________________
There are two types of vessels, submarines and targets.

Top
Page 1 of 1 1


Moderator:  Sealeopard, Kdyer, Bryce, Jochen, Radimus, Howard Bullock, Chris S., Glenn Barnas, Allen, Benny69, Arend_, ShaneEP, Mart 
Hop to:
Shout Box

Who's Online
1 registered (mole) and 36 anonymous users online.
Newest Members
TMcKenzie, dwsykes, zainlait, OgeccuT, raka74
17425 Registered Users

Generated in 0.038 seconds in which 0.013 seconds were spent on a total of 12 queries. Zlib compression enabled.

Search the board with:
superb Board Search
or try with google:
Google
Web kixtart.org