Skip to content
Jesse McKee edited this page May 12, 2024 · 8 revisions

What is a Kotlin Script

A Kotlin script is a file with a file extension of plugin.kts

Scripts are able to make full use of a platforms API as if they were plugins.

Kotlin Scripts are written with regular Kotlin code.

This project also includes API to make your scripts feel more script-like.

Your first Script

Our first script will be a simple hello-world!

Create a file and name it whatever you like, make sure you end it with .plugin.kts

helloworld.plugin.kts

import me.zodd.*

Logger.info("Hello World!")

What does this translate to?

me.zodd.* provides the API wrappers for your scripts.

Logger : This is a wrapper for the logger provided from the platform.

Result

Scripts are evaluated during construction of the plugin.

So the above script will Log during construction.

[XX:XX:XX INFO]: [KotlinScripting] Hello World!

Installing Scripts

Scripts are loaded from the host plugins config directory.

./config/scripting-host/scripts/

Script API

Events

Scripts evaluate during construction of the plugin, so we need some way to use events!

Wrappers are provided to make this convenient to register new events.

How it works

When we write an event we call its closure

onPlayerInteract {
    // this: PlayerInteractEvent
}

This method actually calls another method that registers that event.

// This method (or one like it) is found in the API
fun onPlayerInteract(fn: PlayerInteractEvent.() -> Unit) =
    RegistrationHelper.registerListener(fn)

So if you wanted to wrap your own event you could do something like

val event: PlayerInteractEvent.() -> Unit = {
    // this: PlayerInteractEvent
}

RegistrationHelper.registerListener(event)

Managers

Script Managers are really just wrappers around methods provided by the platform.

Common managers include Tasks (async/sync), Server, and ServiceManager

There are two notable managers available in each platform.

  • Container
  • Logger

Container represents the Host plugin's "Plugin Container"

For Paper, you might recognize this as Plugin on Sponge it is a PluginContainer

Logger is the Host plugin's logger allowing you to log info to console

Usage will depend on the platforms implementation, but for Paper and Sponge Logger.info("") should work!