How do I create a function?
LiveCode for FM comes with some built in functions you can use out of the box or modify to add features.
You can also create your own functions, to provide the functionality your solution needs.
In this lesson we will write a function that will capitalise the first letter of each word in a string. This could be useful for standardising the capitalisation of names or addresses.
To get started open the LiveCode for FM Solution and go to the Functions pane of the Workspace.
- Click the 'Add' button
- Enter the name for the function, I have used "capitaliseWords". Each function needs to have a unique name so it is best to choose something descriptive.
The next step is to add the script for the function.
put fmParam(1) into tString repeat with x = 1 to the number of words in tString put toUpper(character 1 of word x of tString) into character 1 of word x of tString end repeat return tString
- Put the string passed in as a paramter into a variable
- Repeat across each word in the variable (word 1 to word x)
- Put the uppercase version of the first character of each word into the first character of each word
- Return the string
To test the function in the workspace we need to provide a string, the value of fmParam(1) wiil be this string.
- Click the 'Add parameter' button in the Input(s) section. An entry area for Parameter 1 will appear
- Enter a string to be used as an input
- Click the 'Run' button
- The capitalised string is shown in the Ouput section
To test the function close the Workspace and go the the functions layout of the solution.
- Enter the function name
- Set the first parameter to a string
- The returned value is the capitalised version of the string.
- Create a solution with a 'name' field and a 'Capitalise' button.
- Set the button action type to 'Single Step'
- Set the button action to
Set Field[capitaliseTest::name ; LC("capitalisewords" ; capitaliseTest::name)]
- Put a name into the field
- Click the 'Capitalise' button