init
Patches may optionally define an init function that will be called when a patch is saved or updated.
This function can be used to initialize state, or expose functions that can be called from other functions in the patch.
Example
function init() { sup.set("count", 0);}
function main() { return [sup.get("count"), sup.button("add", add)];}
function add() { sup.set("count", sup.get("count") + 1);}In this example, the init function initializes a count to 0. The main function displays the current count and a button to increment the count. The add function increments the count when the button is clicked. If the patch creator updates the patch, the count will be reset to 0.
Public Functions
init can be used to expose functions that can be called from other patches. For example:
function init() { sup.set("count", 0); sup.makePublic([add, getCount]);}
function main() { return [sup.get("count"), sup.button("add", add)];}
function add() { sup.set("count", sup.get("count") + 1);}
function getCount() { return sup.get("count");}In this example, the add and getCount functions are exposed to other functions in the patch by calling sup.makePublic. This allows other patches to call add and getCount directly.
function main() { const countApp = sup.patch("cm37fypg7000108l2fwt82751"); // patch ID countApp.add(); return countApp.getCount();}