Using lists in the library
It will often be useful to return more that a single piece of data from a library handler.
Next we will update the sayHello
handler to take a string containing a comma separated list of names, and return a LiveCode Builder list with an element containing a Hello message for each name passed in.
Updating the return type
The first step is to update the sayHello
handler definition.
We will be returning a List rather than a String so update the return type.
We also want to be able to pass more than one name in so update the parameter name to pNames.
Defining variables
We will be using 3 variables in the handler
- tNameList – a list variable created from the pNames parameter
- tMessage – the list variable that will be returned, with an element holding a messgae for each name passed in in pNames
- tElement – a string variable used to iterate over the elements of tNameList
Add variable definitions for these 3 variables.
Creating a List from a String
We want to convert the String parameter into a List. We can do this using the split statement, which splits the string into a list of strings, using the specified delimiter.
We know the pNames parameter is a command separated list of names so we split pNames by comma to create a List variable.
end handler
Building a List
Next we want to create a list of messages, with an element for each name.
- Loop over each element in tNameList
- Construct a “Hello” message using the current element
- Append it to the end of the list using the push statement.
- Return the list of messages
return tMessage end handler
Testing the library
Compile the library using the Extension Builder.
- Open the Extension Builder from the Tools menu.
- Load the helloWorldLibary.lcb file
- Click Test.
- This will load the library and create a test stack.
- Add a button to the test stack.
- Set the code of the button to
-
- Add a breakpoint to the end mouseUp line so you can view the array in the Variable Watcher.
Note: Remember that LCB lists are converted to numerically keyed arrays in LiveCode Script.