Lua Scripting with Capacity
Lua can be used to write custom functionality within Capacity. While this is an incredibly powerful feature, the usability of the current process is difficult. This will be improved with the upcoming scripting features being added to Capacity.
1. Write a function in Lua.
- Here is a tutorial site for Lua: https://www.tutorialspoint.com/lua/index.htm
- A convenient way to write and test your function is to use Replit.
- Here is a simple script to test if a number is within an hi/low value range
2. Create a new API to call the script from Capacity. This will need to be done from an existing app, or you will need to create a new one. I am going to create a new app to hold my functions.
3. Next I create an api to call my function. I am giving it the same name as my Lua function, but that is not necessary.
4. We are going to POST to the API endpoint {{sys.relay_host}}/?service_name=lua-server&service_path=/1/
5. Now we need to turn our script text into escaped JSON to pass it to this API, which basically means we are going to convert carriage returns and newlines into characters like “/r” and “/n”. This can be done using JSON Escape. After Escaping my function it looks like this.
6. Now we need to make the call to the endpoint API using the following format { "code":" response=func.json_encode({response=)})","":{{your input}} }. Note: If the inputs have a string data type, use this format: "": “{{your input}}”
- Here is what the function looks like in Capacity.
- Notice the input variables show up in the API inputs section where you can give them display names and decide if they are required.
7. Validate that you have pressed “Activate API”, and also published the App
8. Now you can enter some test values to see if it works and test the API
9. If you receive an internal server error, double check the format of what you passed into the API. This process is error prone.
10. In order to use the response you will need to store it as an output by tying it to the JSON path. To find the path we suggest using JSON Path Finder
11. Click on the value you want to retrieve and copy the path back to Capacity. Change the first character to be a “$”. Set the display name of the variable. This is what you will see in the conversations you create.
12. Enable your app
13. Create a guided conversation and add your app to call your API as you would any other app.