### Paired setup and teardown with `on register` and `on end` Source: https://github.com/ahmadmsaleem/sklambda/wiki/Examples Shows the paired setup and teardown callbacks for a listener. `on register:` fires when the listener becomes active (at the `register` command, not at the `set`), and `on end:` fires when it stops. The `owner:` entry makes the listener appear under `listeners owned by` and auto-cleans on quit. ```applescript command /onregister: trigger: set {_p} to sender send "arming a watcher with matched setup + teardown..." to {_p} set {reg_demo::%{_p}%} to listener for block break where player is {_p}: owner: {_p} # makes it "yours": shows up under `listeners owned by` and auto-cleans on quit triggers: 3 on register: send "[setup] watcher armed, break 3 blocks" to {_p} on trigger: send "%remaining triggers% blocks left" to {_p} on completion: send "all 3 broken!" to {_p} on end: send "[teardown] watcher gone (%end reason%)" to {_p} register {reg_demo::%{_p}%} # <- 'on register' fires here, not at the `set` above ``` -------------------------------- ### Reduce with a starting value using `reduced with … from` Source: https://github.com/ahmadmsaleem/sklambda/wiki/List-Operations Sets a starting value for the fold. The lambda runs once for every element, combining the start value with the first element. An empty list returns the start value, and the start can be a different type than the elements. ```applescript set {_total} to (3, 5, 2) reduced with {_add} from 100 # add(100, 3) = 103, add(103, 5) = 108, add(108, 2) = 110 -> {_total} is 110 ``` -------------------------------- ### Listener lifecycle with `on register:` and `on end:` Source: https://github.com/ahmadmsaleem/sklambda/wiki/Listeners Shows `on register:` and `on end:` callbacks. `on register:` runs once when the listener starts (on `register`, not when defined), and `on end:` always runs when the listener stops. Pairing them keeps setup and teardown in one place. ```applescript set {watch::%{_p}%} to listener for block break where player is {_p}: triggers: 3 on register: send "watcher armed, break 3 blocks" to {_p} on trigger: send "%remaining triggers% to go" to {_p} on end: send "watcher gone (%end reason%)" to {_p} register {watch::%{_p}%} # on register: fires here, not at the set above ``` -------------------------------- ### Start background work with future of calling lambda Source: https://github.com/ahmadmsaleem/sklambda/wiki/Async Runs a lambda on a background thread immediately and returns a future. The lambda must be pure (no Bukkit API). Arguments are read on the main thread before work starts. ```applescript set {_hash} to lambda (payload: string) -> string: return {_payload} hashed with SHA-256 # pure compute, safe off-thread set {_f} to future of calling lambda {_hash} with "hello" ``` -------------------------------- ### Counting quantifier examples Source: https://github.com/ahmadmsaleem/sklambda/wiki/Predicates Shows at least, exactly, and at most forms. Each checks how many predicates in the list pass. ```applescript if at least 2 of {requirements::*} passes for {_p}: # two or more hold send "access granted" to {_p} if exactly 3 of {requirements::*} passes for {_p}: # all three, no more, no less send "full clearance" to {_p} if at most 0 of {requirements::*} passes for {_p}: # not a single one send "you meet none of them" to {_p} ``` -------------------------------- ### Quantifier examples: all, any, none Source: https://github.com/ahmadmsaleem/sklambda/wiki/Predicates Shows the three quantifier forms: all of, any of, and none of. Each changes the pass condition for the list. ```applescript if all of {mod::*} passes for {_p}: # every check passes ... if any of {mod::*} passes for {_p}: # at least one passes ... if none of {mod::*} passes for {_p}: # not a single one passes ... ``` -------------------------------- ### Scan a list with a starting value using `scanned with … from` Source: https://github.com/ahmadmsaleem/sklambda/wiki/List-Operations Starts the scan from a seed value. The seed appears first in the result, followed by one result per element. Useful for running balances and cumulative totals. Added in 1.2.0. ```applescript set {_running::*} to (3, 5, 2) scanned with {_add} from 100 # 100, add(100, 3) = 103, add(103, 5) = 108, add(108, 2) = 110 -> 100, 103, 108, 110 ``` -------------------------------- ### Skript: Command visibility with show only, hide, and reset Source: https://github.com/ahmadmsaleem/sklambda/wiki/New-Features Skript example showing how to control command visibility: use 'show only' with permission conditions, hide namespaced commands via a lambda, temporarily hide commands from a player during damage, and reset visibility with a custom command. ```applescript on load: # groups: a player sees the commands of every group they are in show only commands "help", "msg" and "tpa" where player has permission "group.default" show only commands "ban", "kick" and "mute" where player has permission "group.mod" # hide plugin:command labels like essentials:warp set {_namespaced} to lambda (cmd: text): {_cmd} contains ":" hide commands where {_namespaced} passes # no escaping to spawn in the middle of a fight on damage of player: hide commands "spawn" and "home" from victim wait 10 seconds show commands "spawn" and "home" to victim command /resetcommands: trigger: reset command visibility ``` -------------------------------- ### Slide a window over a list with `window N of ... by S` Source: https://github.com/ahmadmsaleem/sklambda/wiki/List-Operations `window N of %list% by S` slides one element at a time instead of jumping whole chunks. Window 1 is elements 1 to S, window 2 is elements 2 to S+1, and so on. This example shows windows 1 and 2 of a 7-element list with window size 3. ```applescript set {_w1::*} to window 1 of {_items::*} by 3 # a, b, c set {_w2::*} to window 2 of {_items::*} by 3 # b, c, d ``` -------------------------------- ### Save and register a listener Source: https://github.com/ahmadmsaleem/sklambda/wiki/Listeners Defines a listener without starting it, then starts it with register. The listener sends chat messages to console and cancels the event. Use unregister {var} to stop it. ```applescript set {chat_log} to listener for chat: on trigger: send "[chat] %sender%: %message%" to console cancel event register {chat_log} ``` -------------------------------- ### Using a function reference as a lambda Source: https://github.com/ahmadmsaleem/sklambda/wiki/Lambdas Defines a Skript function and uses a function reference as a lambda. A function reference with arguments binds them as leading arguments, similar to 'with ... bound'. The example shows calling the bound function and using it in a reduce operation. ```applescript function add(a: number, b: number) :: number: return {_a} + {_b} set {_add5} to the function "add" called with 5 set {_x} to call lambda {_add5} with 10 # 15 set {_sum} to (1, 2, 3) reduced with (the function "add") # 6 ``` -------------------------------- ### Count pages and windows, then loop over pages Source: https://github.com/ahmadmsaleem/sklambda/wiki/List-Operations `page count of %list% by S` returns the number of pages, rounded up so a partial last page counts. `window count of %list% by S` equals `length - S + 1`. The example also shows looping over the page count to build each page, which is useful for filling a GUI menu. ```applescript set {_pages} to page count of {_items::*} by 3 # 3 (7 items -> 3, 3, 1) set {_windows} to window count of {_items::*} by 3 # 5 (7 - 3 + 1) loop (page count of {_items::*} by 3) times: set {_page::*} to page loop-value of {_items::*} by 3 # ... build GUI page loop-value from {_page::*} ``` -------------------------------- ### First diamond wins: listen for block break with countdown Source: https://github.com/ahmadmsaleem/sklambda/wiki/Examples Starts a 60-second listener for a block break event. The listener ends early with `cancel listener` when the goal is met, or by timeout. No `triggers:` is needed. ```applescript command /firstdiamond: trigger: set {_p} to sender send "break a diamond ore within 60s to win" to {_p} listen for block break where event-player is {_p}: countdown: 60 seconds on trigger: if event-block is diamond ore: give 1 diamond to {_p} send "you got one!" to {_p} cancel listener on timeout: send "time's up" to {_p} ``` -------------------------------- ### Run lambda with `run` and ignore return value Source: https://github.com/ahmadmsaleem/sklambda/wiki/Lambdas Use `run lambda` to execute a lambda for its side effects, discarding any return value. The example runs `{_greet}` with the `player` argument. ```applescript run lambda {_greet} with player ``` -------------------------------- ### negated predicate example Source: https://github.com/ahmadmsaleem/sklambda/wiki/Predicates Creates a predicate that passes when the original fails, then uses it in an if condition. The negated predicate can be stored and reused. ```applescript set {_is-op} to lambda (p: player): {_p} is op set {_not-op} to negated {_is-op} if {_not-op} passes for player: send "you're not staff" to player ``` -------------------------------- ### Listen for chat and send message to console Source: https://github.com/ahmadmsaleem/sklambda/wiki/Listeners Starts listening for chat immediately and runs the body each time someone chats. This listener listens forever and for everyone unless limited. ```applescript listen for chat: on trigger: send "%message%" to console ``` -------------------------------- ### Lambda returning a list with `call` and `results of calling` Source: https://github.com/ahmadmsaleem/sklambda/wiki/Lambdas A lambda body can return a list. `call lambda` returns the first value, while `results of calling lambda` returns all values. The example defines a lambda returning a list of medals and shows both retrieval methods. ```applescript set {_top3} to lambda -> object: set {_best::*} to "gold", "silver", "bronze" return {_best::*} set {_first} to call lambda {_top3} # gold set {_all::*} to results of calling lambda {_top3} # gold, silver, bronze ``` -------------------------------- ### Call lambda with multiple arguments Source: https://github.com/ahmadmsaleem/sklambda/wiki/Lambdas When a lambda takes more than one argument, separate them with commas. The example defines a lambda that adds two numbers and calls it with 3 and 4, resulting in `{_total}` being 7. ```applescript set {_sum} to lambda (a: number, b: number) -> number: return {_a} + {_b} set {_total} to call lambda {_sum} with 3, 4 # {_total} is 7 ``` -------------------------------- ### Wait for all or any of multiple futures Source: https://github.com/ahmadmsaleem/sklambda/wiki/Async `wait for all of` continues when every future resolves; `wait for any of` continues when the first succeeds. For `all of`, `on failure:` runs on the first failure (short-circuits). For `any of`, `on failure:` runs only when every future has failed. Both examples are shown together as they illustrate the two forms. ```applescript wait for all of {_a} and {_b} within 10 seconds: # when-all: every future resolved send "both done: %result of {_a}% and %result of {_b}%" to player on failure: send "one of them broke" to player wait for any of {_jobs::*}: # the first one to succeed send "first result in" to player on failure: send "every job failed" to player ``` -------------------------------- ### Create already settled futures with 'completed future' and 'failed future' Source: https://github.com/ahmadmsaleem/sklambda/wiki/Async Builds a future that is already resolved or already failed, useful for a uniform helper that always returns a future. The first example shows the two constructors; the second shows a lambda that returns a completed future from cache or falls back to a slow lookup. ```applescript set {_hit} to a completed future with "from cache" # already resolved set {_miss} to a failed future with "no such player" # already failed ``` ```applescript set {_lookup} to lambda (p: player) -> object: if {cache::%uuid of {_p}%} is set: return a completed future with {cache::%uuid of {_p}%} return future of calling lambda {_slow-lookup} with {_p} ``` -------------------------------- ### Slice a list into pages with `page N of ... by S` Source: https://github.com/ahmadmsaleem/sklambda/wiki/List-Operations `page N of %list% by S` splits the list into back-to-back chunks of size S and returns the Nth chunk (1-based). The last page may be shorter, and a page past the end is empty. This example shows pages 1, 2, and 3 of a 7-element list with chunk size 3. ```applescript set {_items::*} to "a", "b", "c", "d", "e", "f", and "g" set {_p1::*} to page 1 of {_items::*} by 3 # a, b, c set {_p2::*} to page 2 of {_items::*} by 3 # d, e, f set {_p3::*} to page 3 of {_items::*} by 3 # g ``` -------------------------------- ### Aggregates: seeded reduce and min/max by key lambda Source: https://github.com/ahmadmsaleem/sklambda/wiki/Examples Shows seeded reduce with `reduced with … from` (safe on empty lists, seed can be a different type) and `highest`/`lowest of … by` returning the element with the smallest/largest key. The lambda for reduce runs for every element starting from the seed; on an empty list the lambda never runs and the seed is returned. The `by` key lambda returns the element itself, not the key value. ```applescript command /aggregates: trigger: set {_p} to sender set {_nums::*} to 3, 5, 2, and 8 # seeded reduce: lambda runs for every element, starting from the seed set {_add} to lambda (a: number, b: number) -> number: return {_a} + {_b} send "sum from 100 = %{_nums::*} reduced with {_add} from 100%" to {_p} # 118 clear {_empty::*} send "empty from 0 = %{_empty::*} reduced with {_add} from 0%" to {_p} # 0 (lambda never runs) # min/max by a key lambda: returns the element with the smallest/largest key set {_abs} to lambda (n: number) -> number: return abs({_n}) set {_signed::*} to -7, 3, and -1 send "closest to zero: %lowest of {_signed::*} by {_abs}%" to {_p} # -1 send "farthest from zero: %highest of {_signed::*} by {_abs}%" to {_p} # -7 # players: top by level, hands back the player, not the number set {_score} to lambda (pl: player) -> number: return {_pl}'s level send "top player by level: %highest of all players by {_score}%" to {_p} ``` -------------------------------- ### Firing a watcher on the first poll with initial: false Source: https://github.com/ahmadmsaleem/sklambda/wiki/Examples Uses `initial: false` in a `watch when` watcher to assume the condition started false, so a player already hurt is alerted on the first poll. `initial: true` is the mirror image for `on falling:`. Leaving the entry off gives the old baseline behaviour. Added in 1.4.0. ```applescript command /hurtalert: trigger: set {_p} to sender watch when (health of {_p} < 6) every 1 second within 10 minutes: initial: false on rising: send "low health!" to {_p} on falling: send "back to safe health" to {_p} ``` -------------------------------- ### Lambda default parameter value (step: number = 1) Source: https://github.com/ahmadmsaleem/sklambda/wiki/Examples Defines a lambda with a default parameter value (`step: number = 1`). When the caller omits the trailing argument, the default is used; only trailing arguments can be skipped. The example calls the lambda with and without the second argument, producing 11 and 15 respectively. ```applescript command /defaults: trigger: set {_p} to sender set {_advance} to lambda (value: number, step: number = 1) -> number: return {_value} + {_step} send "advance(10) = %call lambda {_advance} with 10%" to {_p} # step defaults to 1 -> 11 send "advance(10, 5) = %call lambda {_advance} with 10 and 5%" to {_p} # 15 ``` -------------------------------- ### Watch condition with edge-triggered rising/falling events Source: https://github.com/ahmadmsaleem/sklambda/wiki/Examples Polls a condition every second for up to 10 minutes and fires only on transitions: `on rising:` when the condition becomes true and `on falling:` when it becomes false. A condition already true when the watcher starts stays quiet until it goes false and back; add `initial: false` to fire immediately. ```applescript command /lowhealth: trigger: set {_p} to sender send "alerting you whenever you drop below 6 hearts of health." to {_p} watch when (health of {_p} < 6) every 1 second within 10 minutes: on rising: send "low health!" to {_p} on falling: send "back to safe health" to {_p} ``` -------------------------------- ### Shield with hits and time, extendable by golden apple Source: https://github.com/ahmadmsaleem/sklambda/wiki/Examples Implements a shield that blocks damage for 30 seconds or 5 hits, whichever comes first. A second listener reacts to consuming a golden apple to extend the shield's triggers and countdown, using `skip trigger` to ignore other food. Shows saving listeners in variables and starting them with `register`. ```applescript command /shield: trigger: set {_p} to sender send "shielded for 30s or 5 hits. eat a golden apple to extend." to {_p} set {shield::%{_p}%} to listener for damage where victim is {_p}: countdown: 30 seconds triggers: 5 on trigger: cancel event send "blocked! (%remaining triggers% hits, %remaining countdown% left)" to {_p} on completion: send "shield used up" to {_p} on timeout: send "shield expired" to {_p} register {shield::%{_p}%} set {shield_upgrade::%{_p}%} to listener for consume where event-player is {_p}: on trigger: if event-item is not golden apple: skip trigger add 1 to {shield::%{_p}%}'s triggers add 10 seconds to {shield::%{_p}%}'s countdown send "shield upgraded!" to {_p} register {shield_upgrade::%{_p}%} ``` -------------------------------- ### Count passing predicates with at least/at most/exactly N of Source: https://github.com/ahmadmsaleem/sklambda/wiki/Examples Use `at least N of`, `at most N of`, and `exactly N of … passes` to check how many predicates in a list pass. The example builds a list of three lambda predicates and tests it against the sender, sending different messages based on the count. See the Predicates page for the full counting quantifier forms. ```applescript command /access: trigger: set {_p} to sender clear {_reqs::*} add lambda (pl: player): {_pl} is op to {_reqs::*} add lambda (pl: player): {_pl} has permission "group.vip" to {_reqs::*} add lambda (pl: player): {_pl}'s level >= 10 to {_reqs::*} if at least 2 of {_reqs::*} passes for {_p}: send "access granted — met 2+ of the 3 checks" to {_p} else: send "need at least 2 of: op, vip, level 10+" to {_p} if exactly 3 of {_reqs::*} passes for {_p}: send "full clearance — all three" to {_p} if at most 0 of {_reqs::*} passes for {_p}: send "you meet none of them" to {_p} ``` -------------------------------- ### Build skLambda with gradlew Source: https://github.com/ahmadmsaleem/sklambda/blob/main/README.md Builds the project with Gradle, producing a JAR file at build/libs/skLambda-.jar. ```bash ./gradlew build # build/libs/skLambda-.jar ``` -------------------------------- ### failure reason of Source: https://github.com/ahmadmsaleem/sklambda/wiki/Async Gets the failure reason of a future. ```APIDOC ## failure reason of ### Description Returns the text explaining a failure. Returns `nothing` for a pending or successfully resolved future, so it doubles as a failure test. Aliases: `error of`, `failure of`, `exception of`. ### Syntax `failure reason of %future%` ### Parameters - **future** (future) - Required - The future to inspect. ### Example ```applescript if {_f} has failed: send "%failure reason of {_f}%" to console ``` ``` -------------------------------- ### Enable type hints and use a lambda with call lambda Source: https://github.com/ahmadmsaleem/sklambda/wiki/Lambdas Enables Skript's experimental type hints and shows a lambda assigned to a variable, called with an argument, and a deliberate type error that Skript catches at parse time. Without `using type hints`, the bad line loads but is not caught early. ```applescript using type hints command /testlambda: trigger: set {_double} to lambda (n: number) -> number: return {_n} * 2 set {_result} to call lambda {_double} with 5 send "Result: %{_result}%" to sender # This line is a mistake: you can't lowercase a lambda. # With type hints on, Skript catches it as a parse error. set {_bad} to {_double} in lowercase ``` -------------------------------- ### Manual future promise and wait for all of futures Source: https://github.com/ahmadmsaleem/sklambda/wiki/Examples Creates a promise with `a new future`, resolves it with `complete %future% with %object%`, and checks `is pending` / `is done`. Also demonstrates `wait for all of %futures%` to join multiple background jobs; its `on failure:` fires on the first failure without waiting for the rest. ```applescript command /promise: trigger: set {_p} to sender # a promise you resolve yourself set {_token} to a new future if {_token} is pending: send "token not ready yet" to {_p} complete {_token} with "abc-123" if future {_token} is done: send "token = %result of {_token}%" to {_p} # two background jobs, joined into one wait set {_work} to lambda (n: number) -> number: return {_n} * {_n} # pure compute, safe off-thread set {_a} to future of calling lambda {_work} with 6 set {_b} to future of calling lambda {_work} with 9 wait for all of {_a} and {_b} within 10 seconds: send "both done: %result of {_a}% and %result of {_b}%" to {_p} on failure: send "a job failed" to {_p} on timeout: send "a job stalled" to {_p} ``` -------------------------------- ### future of calling lambda Source: https://github.com/ahmadmsaleem/sklambda/wiki/Async Starts a lambda on a background thread and returns a future for its result. ```APIDOC ## future of calling lambda ### Description Runs a lambda on a background thread immediately and returns a future for its result. The lambda must be pure (no Bukkit API). Arguments are read on the main thread before the work starts. ### Syntax `future of calling lambda %lambda% [with %objects%]` ### Parameters - **lambda** (lambda) - Required - The lambda to run in the background. - **objects** (objects) - Optional - Arguments to pass to the lambda. ### Example ```applescript set {_hash} to lambda (payload: string) -> string: return {_payload} hashed with SHA-256 set {_f} to future of calling lambda {_hash} with "hello" ``` ``` -------------------------------- ### With skLambda: listener-based challenge with countdown and triggers Source: https://github.com/ahmadmsaleem/sklambda/blob/main/README.md skLambda version of the same mining challenge. The listener is scoped to this one command run; the counter, timer, and live action-bar readout are built in, and cleanup happens automatically on completion or timeout. Demonstrates the `listen for block break`, `countdown`, `triggers`, `on completion`, and `on timeout` clauses. ```applescript command /challenge: trigger: send "mine 10 stone in 30s" to player listen for block break where event-block is stone: countdown: 30 seconds triggers: 10 every 1 second: send action bar "%remaining triggers% left — %remaining countdown%" to event-player on completion: send "you did it!" to event-player give 1 diamond to event-player on timeout: send "too slow!" to event-player ``` -------------------------------- ### window N of … by S Source: https://github.com/ahmadmsaleem/sklambda/wiki/List-Operations Returns a sliding window of size S starting at position N. ```APIDOC ## window N of … by S ### Description Returns a sliding window of size S starting at position N. Window 1 is elements 1 to S, window 2 is elements 2 to S+1, and so on. ### Syntax `window N of %list% by S` ### Parameters - **N** (integer) - Required - The starting position (1-based) of the window. - **list** (list) - Required - The list to slide over. - **S** (integer) - Required - The size of the window. ### Example ```applescript set {_items::*} to "a", "b", "c", "d", "e", "f", and "g" set {_w1::*} to window 1 of {_items::*} by 3 # a, b, c set {_w2::*} to window 2 of {_items::*} by 3 # b, c, d ``` ### Notes - Added in 1.2.0. ``` -------------------------------- ### Get highest and lowest element by a key with a lambda Source: https://github.com/ahmadmsaleem/sklambda/wiki/List-Operations Use `highest of ... by` and `lowest of ... by` to get the single element with the largest or smallest key, as scored by a lambda. The result is the element itself, not the score. Ties keep the first element found, and an empty list returns nothing. This is more efficient than sorting when only the extreme element is needed. ```applescript set {_score} to lambda (p: player) -> number: return {_p}'s level set {_top} to highest of all players by {_score} # the highest-level player set {_bottom} to lowest of all players by {_score} # the lowest-level player ``` -------------------------------- ### Enable lambda and listener features in config.yml Source: https://github.com/ahmadmsaleem/sklambda/wiki/Configuration Default configuration for skLambda's config.yml. Both feature toggles default to true and require a full server restart to take effect because syntax is handed to Skript once at startup and cannot be unregistered afterwards. Turning both off makes skLambda warn in the console and do nothing. ```yaml # [RESTART] # Lambdas: the `lambda` type, inline lambdas, default parameters, call/run, `passes` # (incl. at-least/at-most/exactly), `negated`, `bound`, `pipe`, the lambda list # operations (map/reduce/scan/zip/sort/min/max, page/window, taken/dropped while), # always()/never(), and the futures (future of calling, a new future, completed and # failed futures, result of, complete, fail, failure reason of, then, the future # conditions) and `wait for` blocks. lambda: true # [RESTART] # Listeners: the `listen` section, register/unregister/pause/resume (incl. by owner), # on register / on end, remaining triggers / remaining countdown, cooldown/owner access, # active-listener queries, listener origin (script/creation date/age), state checks, # and the `watch` / `watch when` watchers. listener: true ``` -------------------------------- ### Equivalent syntax for calling a lambda Source: https://github.com/ahmadmsaleem/sklambda/wiki/Lambdas These four lines are equivalent ways to call a lambda and retrieve its value. Choose whichever reads best in your code. ```applescript set {_x} to call lambda {_double} with 5 set {_x} to invoke lambda {_double} with 5 set {_x} to calling lambda {_double} with 5 set {_x} to the result of calling lambda {_double} with 5 ``` -------------------------------- ### Invoke lambda without arguments Source: https://github.com/ahmadmsaleem/sklambda/wiki/Lambdas Use `invoke lambda` to call a lambda that takes no arguments. The example invokes `{_now}` and stores the result in `{_t}`. ```applescript set {_t} to invoke lambda {_now} ``` -------------------------------- ### Clean up listeners with unregister commands Source: https://github.com/ahmadmsaleem/sklambda/wiki/Examples Shows how to spawn multiple listeners and then stop them in bulk. Includes commands to unregister the last created listener and to unregister all listeners (server-wide, use with care). Use `/sklambda listeners` to inspect active listeners. ```applescript command /spawnwatchers: trigger: listen for block break: on trigger: send "block broken" to player listen for chat: on trigger: send "chat seen" to player send "two watchers running, try /sklambda listeners" to player command /undolast: trigger: unregister the last created listener send "stopped the last watcher" to sender command /listenerpanic: trigger: unregister all listeners # stops EVERY listener on the server send "all listeners cleared" to sender ``` -------------------------------- ### Wrap a function with `function lambda` Source: https://github.com/ahmadmsaleem/sklambda/wiki/Lambdas Wraps an existing Skript function in a lambda using `function lambda "double"`, then calls, runs, and stores it. The function is looked up by name when the lambda runs. ```applescript function double(amount: number) :: number: return {_amount} * 2 set {_reward} to function lambda "double" set {_x} to call lambda {_reward} with 5 # 10 run lambda {_reward} with 21 # just runs it add {_reward} to {_doublers::*} # store it for later ``` -------------------------------- ### Call lambda with `call` and retrieve value Source: https://github.com/ahmadmsaleem/sklambda/wiki/Lambdas Use `call lambda` to invoke a lambda and store its return value. The example shows a lambda `{_double}` called with argument 5, resulting in `{_x}` being 10. ```applescript set {_x} to call lambda {_double} with 5 # {_x} is now 10 ``` -------------------------------- ### Owner expression and bulk pause/resume Source: https://github.com/ahmadmsaleem/sklambda/wiki/Examples Shows how to set an owner on listeners with `owner:` and how to read it back with `owner of %listener%`. The `pause all listeners owned by` and `resume all listeners owned by` commands freeze or revive every listener scoped to that owner in one line. ```applescript command /guardon: trigger: set {_p} to sender listen for block break: owner: {_p} where: player is {_p} on trigger: send "you broke %event-block%" to {_p} listen for chat: owner: {_p} where: player is {_p} on trigger: send "you said: %message%" to {_p} send "two guards online, owned by %owner of the last created listener%." to {_p} command /guardpause: trigger: pause all listeners owned by sender # freeze every listener scoped to you, one line send "your guards are paused" to sender command /guardresume: trigger: resume all listeners owned by sender send "your guards are back" to sender ``` -------------------------------- ### Lambda Calling Operations Source: https://github.com/ahmadmsaleem/sklambda/wiki/Lambdas Documentation for calling lambdas in Skript, including the `call`, `run`, and `results of calling` operations. ```APIDOC ## call lambda ### Description Calls a lambda and returns its value. This is used when you want the result of the lambda. ### Syntax `call lambda {_lambda} with ` ### Parameters - **{_lambda}** (lambda) - Required - The lambda to call. - **arguments** (any) - Required - The arguments to pass to the lambda, separated by commas. ### Example ```applescript set {_x} to call lambda {_double} with 5 # {_x} is now 10 ``` ### Notes - Equivalent forms: `invoke lambda {_lambda} with `, `calling lambda {_lambda} with `, and `the result of calling lambda {_lambda} with `. - Since 1.5.0, `call lambda {_x}` and `invoke lambda {_x}` can also be used on their own line. - When the lambda returns a list, `call lambda` returns only the first value. ``` ```APIDOC ## run lambda ### Description Runs a lambda without returning its value. This is used when you only care about the side effects of the lambda. ### Syntax `run lambda {_lambda} with ` ### Parameters - **{_lambda}** (lambda) - Required - The lambda to run. - **arguments** (any) - Required - The arguments to pass to the lambda, separated by commas. ### Example ```applescript run lambda {_greet} with player ``` ### Notes - Any return value from the lambda is discarded. ``` ```APIDOC ## results of calling lambda ### Description Calls a lambda that returns a list and returns all values in the list. This is the plural form of `call lambda`. ### Syntax `results of calling lambda {_lambda} with ` ### Parameters - **{_lambda}** (lambda) - Required - The lambda to call. - **arguments** (any) - Required - The arguments to pass to the lambda, separated by commas. ### Example ```applescript set {_all::*} to results of calling lambda {_top3} # gold, silver, bronze ``` ### Notes - Added in 1.5.0. Before, a list return failed with a confusing parse error and then handed back nothing. ``` -------------------------------- ### Page and window a list in Skript Source: https://github.com/ahmadmsaleem/sklambda/wiki/Examples Demonstrates `page N of … by S` for non-overlapping chunks and `window N of … by S` for overlapping slices. Uses `page count` to drive a loop; the second sliding window of 3 yields b, c, d. ```applescript command /pagelist: trigger: set {_p} to sender set {_items::*} to "a", "b", "c", "d", "e", "f", and "g" set {_per} to 3 send "%size of {_items::*}% items, %page count of {_items::*} by {_per}% pages of %{_per}%:" to {_p} loop (page count of {_items::*} by {_per}) times: send "page %loop-value%: %page loop-value of {_items::*} by {_per}%" to {_p} send "2nd sliding window of 3: %window 2 of {_items::*} by 3%" to {_p} # b, c, d ``` -------------------------------- ### Capturing nearby variables in a lambda Source: https://github.com/ahmadmsaleem/sklambda/wiki/Lambdas Lambda captures a snapshot of local variables at definition time. The example captures {_tax} and uses it to compute a total of 120 for a price of 100; changing the local afterwards does not affect the lambda. ```applescript set {_tax} to 0.2 set {_with-tax} to lambda (price: number) -> number: return {_price} * (1 + {_tax}) # {_tax} is captured here set {_total} to call lambda {_with-tax} with 100 # 120 ``` -------------------------------- ### Recursive lambda with self-passing pattern Source: https://github.com/ahmadmsaleem/sklambda/wiki/Lambdas Recursive lambda that takes itself as the first argument and calls that parameter inside the body. The self-passing pattern is the intended way to recurse; the example computes factorial of 5 and stores 120 in {_r}. ```applescript set {_fact} to lambda (self: object, n: number) -> number: if {_n} <= 1: return 1 return {_n} * (call lambda {_self} with {_self}, {_n} - 1) set {_r} to call lambda {_fact} with {_fact}, 5 # {_r} is 120 ``` -------------------------------- ### Create a lambda factory that returns a lambda Source: https://github.com/ahmadmsaleem/sklambda/wiki/Lambdas Demonstrates a lambda that returns another lambda, creating a factory. The inner lambda captures the outer parameter, so the returned lambda always adds the captured value. ```applescript set {_make_adder} to lambda (n: number) -> object: set {_inner} to lambda (x: number) -> number: return {_x} + {_n} return {_inner} set {_plus5} to call lambda {_make_adder} with 5 set {_r} to call lambda {_plus5} with 10 # {_r} is 15 ``` -------------------------------- ### Cooldown example: ignore rapid repeats Source: https://github.com/ahmadmsaleem/sklambda/wiki/Listeners Sets a minimum gap between fires. Events arriving during the cooldown are ignored: they don't run `on trigger:` and don't count toward `triggers:`. Useful for events that can fire many times in a quick burst. ```applescript listen for damage where victim is {_p}: cooldown: 1 second # at most one counted hit per second on trigger: send "hit!" to {_p} ``` -------------------------------- ### Unregister stale listeners older than 10 minutes Source: https://github.com/ahmadmsaleem/sklambda/wiki/Listeners Finds and unregisters stale listeners older than 10 minutes. `age of` counts from creation, not registration, so a listener declared with `set {_x} to a listener on ...` and registered later already has an age before it starts listening. ```applescript loop all active listeners: if age of loop-value > 10 minutes: send "stale listener from %script of loop-value%" to console unregister loop-value ``` -------------------------------- ### Perform list operations with lambdas and predicates Source: https://github.com/ahmadmsaleem/sklambda/wiki/Examples Demonstrates list operations with lambdas and predicates: map with `mapped with`, filter with `where [... passes for input]`, reduce with `reduced with`, count and find via `number of` and `first element of`, and sort with `sorted by`. The lambda for sorting pulls a key from each element (e.g., player level). ```applescript command /listops: trigger: set {_p} to sender set {_nums::*} to 3, 5, 2, and 8 # map: transform every element set {_double} to lambda (n: number) -> number: return {_n} * 2 set {_doubled::*} to {_nums::*} mapped with {_double} send "doubled: %{_doubled::*}%" to {_p} # 6, 10, 4, 16 # filter: keep only matching elements (Skript's own `where`, fed a predicate) set {_big} to lambda (n: number): {_n} > 3 set {_kept::*} to {_nums::*} where [{_big} passes for input] send "over 3: %{_kept::*}%" to {_p} # 5, 8 # reduce: fold the whole list to one value set {_add} to lambda (a: number, b: number) -> number: return {_a} + {_b} set {_total} to {_nums::*} reduced with {_add} send "sum = %{_total}%" to {_p} # 18 # count / first: same predicate via Skript's `number of` and `first element of` send "%number of ({_nums::*} where [{_big} passes for input])% numbers over 3" to {_p} send "first over 3: %first element of ({_nums::*} where [{_big} passes for input])%" to {_p} # sort: order a list by a key the lambda pulls out of each element set {_score} to lambda (pl: player) -> number: return {_pl}'s level set {_ranked::*} to all players sorted by {_score} # lowest level first send "ranked by level: %{_ranked::*}%" to {_p} ``` -------------------------------- ### Wrap function in lambda with function lambda Source: https://github.com/ahmadmsaleem/sklambda/wiki/Examples Wraps an existing function `double` into a lambda using `function lambda "double"`, then calls it with 5 and sends the result. Shows how to reuse a function as a lambda. ```applescript function double(amount: number) :: number: return {_amount} * 2 command /functionlambda: trigger: set {_reward} to function lambda "double" set {_x} to call lambda {_reward} with 5 send "double(5) = %{_x}%" to player ``` -------------------------------- ### Check future state with 'is pending' and 'has failed' Source: https://github.com/ahmadmsaleem/sklambda/wiki/Async Uses the conditions `future %future% is pending` and `%future% has failed` to distinguish not-done from done-with-nothing. The leading `future` is optional but recommended when running SkBee to avoid conflict with its `%advancementprogress% is done` condition. ```applescript if future {_token} is pending: send "not ready yet" to player if {_f} has failed: send "background job blew up: %failure reason of {_f}%" to player ``` -------------------------------- ### Using a skript-reflect section as a lambda Source: https://github.com/ahmadmsaleem/sklambda/wiki/Lambdas Defines a skript-reflect section that takes an argument and returns a value, then uses it with map and future operations. The section's arguments are declared with 'with arguments variables' and its return value is used as the result. ```applescript create new section with arguments variables {_n} stored in {_double}: return {_n} * 2 set {_doubled::*} to (1, 2, 3) mapped with {_double} # 2, 4, 6 set {_f} to future of calling lambda {_double} with 21 # runs it off the main thread ``` -------------------------------- ### Fire immediately with 'initial:' in watcher Source: https://github.com/ahmadmsaleem/sklambda/wiki/Async Uses 'initial:' to assume a state before the first poll, so an already-true condition fires 'on rising' immediately. 'initial: false' fires on first poll if true; 'initial: true' is the mirror for 'on falling'. Added in 1.4.0. ```applescript watch when (health of player < 6) every 1 second: initial: false on rising: send "low health!" to player # fires immediately if already hurt ```