# Home

Lukkit allows developers to create plugins for the Spigot API in an efficient and effective manner using the Lua scripting language. Lua is a quite simple scripting language that even beginners can master, which makes it a great option for newer developers who want to get started with plugin development.

### Why should I choose Lukkit?

Lua is a simple scripting language for both beginners and experienced developers Creating simple, or even complex, Lukkit plugins take almost no time at all compared to Java The entire Spigot API is supported right out of the box, meaning no add-ons are needed

### Where do I start?

Get started with Lukkit through our [getting started](/getting-started) guide. We offer extensive documentation and a multitude of examples to get you going with Lukkit plugin development. For support or more information, contact us via Discord.


# Getting Started

This guide will walk you through the basic steps of creating your first plugin using Lukkit. Please note that this is not a comprehensive guide and you will not learn everything there is to know about Lukkit just by following the examples provided.


# Installing Lukkit

The source for Lukkit can be found on GitHub. Releases can be found on GitHub aswell or on the [SpigotMC resource page](https://www.spigotmc.org/resources/lukkit.32599/). However, a direct download is also available [here](https://as1.al1l.com/Lukkit/Lukkit-2.0.jar). Recent beta releases can also be found on [Google Drive](https://drive.google.com/uc?id=1TIHkS9WdDZPzkn-rB_nByJnztJbVY8vx\&export=download).


# Your First Plugin

Create a folder inside of your plugins folder. You can name this folder whatever you like as long as it has the `.lkt` extension. For example, `MyFirstLukkitPlugin.lkt` would be a great name to start with. Inside of the folder you have just created, create two more new files named `main.lua` and `plugin.yml`. These files will be used to control and configure your Lukkit plugin.

### Plugin Configuration

The `plugin.yml` file is where information on your plugin, such as the description, author and version will be stored. The format of this file follows the same structure as that of the Bukkit or Spigot `plugin.yml`. However, unlike the `plugin.yml` in Bukkit and Spigot, you are not required to fill out the commands section. More information on the `plugin.yml` file can be found [here](https://bukkit.gamepedia.com/Plugin_YAML), do not include the `commands` section as it will cause errors.

An example of a `plugin.yml` file looks like:

{% code title="plugin.yml" %}

```yaml
main: main.lua
version: 1.0
name: My-First-Lukkit-Plugin
description: My very first Lukkit plugin.
author: YourName
```

{% endcode %}

### Main Lua File

The main Lua file is defined in your `plugin.yml` file and is the first file that is run when your plugin starts. This file does not have to be called name, as long as the name defined in your `plugin.yml` file matches that of your main file.

An example of a main Lua file with the `onEnable` and `onDisable` events looks like:

{% code title="main.lua" %}

```lua
plugin.onEnable(function()
  logger.info("My first plugin is enabled!")
end)

plugin.onDisable(function()
  logger.info("My first plugin is disabled!")
end)
```

{% endcode %}

### Commands

Creating commands in Lukkit is simple and requires only three lines of code. When creating a command in Lukkit, information about the command is stored in objects, such as the name and description. More information about commands can be found [here](/commands).

An example of a main Lua file with a command looks like:

{% code title="main.lua" %}

```lua
plugin.onEnable(function()
  logger.info("My first plugin is enabled!")
end)

plugin.onDisable(function()
  logger.info("My first plugin is disabled!")
end)

local testCommand = plugin.addCommand({name="hello",description="Hello world"}, function(cmd)
    plugin.getServer():broadcastMessage("Hello, world!")
end)

```

{% endcode %}

### Events

Just like creating commands, listening for events in Lukkit is very simple and only requires three lines of code. With events and commands, you can also get information about the player or other information that is returned in the event. More information about events can be found [here](https://lukkit.net/Events).

An example of a main Lua file with an event looks like:

{% code title="main.lua" %}

```lua
plugin.onEnable(function()
  logger.info("My first plugin is enabled!")
end)

plugin.onDisable(function()
  logger.info("My first plugin is disabled!")
end)

local testCommand = plugin.addCommand({name="hello",description="Hello world"}, function(cmd)
    plugin.getServer():broadcastMessage("Hello, world!")
end)

plugin.registerEvent("BlockBreakEvent", function(event)
    event:getPlayer():sendMessage("You broke a block")
end)
```

{% endcode %}


# Packing and Publishing


# Storage

The storage system that has been implemented into Lukkit allows you to create configuration and storage files for your plugin. Creating a file super simple, all you have to do is call the `plugin.getStorageObject(file: string)` method. The file parameter is relative to the data folder for the plugin and has support for both YAML and JSON files.


# The StorageObject

This is the object returned when calling [plugin.getStorageObject(file: string)](https://github.com/artex-development/docs.lukkit.net/tree/872d59d6ba1d99b239c03950ebfcb8df546f66aa/storage/Globals/README.md#plugingetstorageobjectfile-string). Here it is represented as `storage`.

## `storage:getType()`: `"yaml"` or `"json"`

Returns the type of the storage object, it will be either `"yaml"` or `"json"`.

## `storage:exists(path: string)`: boolean

Returns true if the path exists in the storage file and false if not

## `storage:setDefaultValue()`: boolean

Sets the default value for a path. Returns true if the value is set and false if not

## `storage:setValue(path: string, value: any)`: boolean

Sets the value of the path in the storage file. Returns false if there was an error setting the value.

## `storage:getValue(path: string)`: any

Gets the value from the storage file from its path.

## `storage:clearValue(path: string)`: boolean

Deletes the value from the storage file from its path. Returns false if there was an error setting the value.

## `storage:save()`

Save the current storage object to its file. It is recommended to do this on plugin disable.


# Example

In this example, a storage object is created for the `config.yml` file and sets the default value `join-message`. Then when the [player event](https://github.com/artex-development/docs.lukkit.net/tree/872d59d6ba1d99b239c03950ebfcb8df546f66aa/storage/Events/README.md#player) `PlayerJoinEvent` is called it gets the storage value from the [storage object](/storage/example#storageobject), replaces `%s` with the player name and sets it to the join message.

```lua
-- Create a storage object with the file "config.yml"
pluginConfig = plugin.getStorageObject("config.yml")

-- Set the default to join message and save the config if it is not already in there
if pluginConfig:setDefaultValue("join-message", "%s joined the game!") then
    pluginConfig:save()
end

-- Make event for when players join
plugin.registerEvent("PlayerJoinEvent", function(event)
    -- Set the join message based on the config value
    event:setJoinMessage(string.format(pluginConfig:getValue("join-message"), event:getPlayer():getDisplayName()))
end)
```


# Commands

Lukkit allows you to create simple or even complex commands using just a few simple lines of Lua. Commands created using Lukkit work just the same as a command creating via the Spigot API in Java would. Specifying a name for each command is required, but the other options allow you to extend the command and are optional.

Commands can be created using the [`plugin.addCommand()`](https://docs.lukkit.net/globals/global-variables/plugin) method. Two parameters are required for this method, the first being a [command options](https://docs.lukkit.net/commands/command-options) table and the second a callback function with a single parameter known as the [CommandEvent](https://docs.lukkit.net/commands/command-event).


# Command Options

The command options table is the first required parameter for the [`plugin.addCommand()`](https://docs.lukkit.net/globals/global-variables/plugin) method and the following is a list of specifications that can be made using the table.

Remember that name is the one specification that is required for each command.

| Specification     | Description                                                                                      |
| ----------------- | ------------------------------------------------------------------------------------------------ |
| name              | Name of the command                                                                              |
| description       | Description of the command                                                                       |
| usage             | Message displayed when the command has been executed in an incorrect manner                      |
| permission        | Permission node required to execute the command                                                  |
| permissionMessage | Message displayed when the user executing the command does not have the required permission node |
| maxArgs           | The maximum amount of arguments for the command                                                  |
| minArgs           | The minimum amount of arguments for the command                                                  |
| runAsync          | True or false, whether the function should be run in an asynchronous manner                      |


# Command Event

The command event is passed through the callback function of the [plugin.addCommand()](/globals/global-variables/plugin) method. This event has certain properties that can help you when creating the function of your command. This even is known as `commandEvent` in the [examples](/commands/examples). Look there to see how it is used.

* **`commandEvent.isPlayerSender()`: boolean**\
  Returns true if the sender of the command is a player or false otherwise.
* **`commandEvent.isConsoleSender()`: boolean**\
  Returns true if the sender of the command is the console or false otherwise.
* **`commandEvent.isBlockSender()`: boolean**\
  Returns true if the sender of the command is a block (e.g. command block) or false otherwise.
* **`commandEvent.isEntitySender()`: boolean**\
  Returns true if the sender of the command is an entity (can be a player) or false otherwise.
* **`commandEvent.getSender()`:** [**org.bukkit.command.CommandSender**](https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/command/CommandSender.html)\
  Returns the sender of the command.
* **`commandEvent.getArgs()`: array**\
  Returns the arguments of the command.
* **`commandEvent.getCommand()`: string**\
  Returns the name of the command.


# Examples

The following are basic usage examples for commands, the command options and the CommandEvent. Please note that, in each of these examples, the value returned from [`commandEvent.getSender()`](https://docs.lukkit.net/commands/commandevent) is always a player.

## Command Options

This example contains a command in which all command option specifications have been filled.

```lua
plugin.addCommand({name="command", description="Execute the command /command", usage="/command", permission="commands.command", permissionMessage="You cannot execute /command", maxArgs=0, minArgs=0, runAsync=false}, function(commandEvent)
    commandEvent.getSender():sendMessage("You executed /" .. commandEvent.getCommand());
end)
```

## Arguments

This example contains a command that requires arguments to be specified from the player. The list of arguments is returned when calling [`commandEvent.getArgs()`](https://docs.lukkit.net/commands/commandevent) and thus we can use `[1]` to get the first argument that was specified.

```lua
plugin.addCommand({name="command", description="Execute the command /command", usage="/command <message>", minArgs=1}, function(commandEvent)
    commandEvent.getSender():sendMessage("You executed /" .. commandEvent.getCommand() .. " with the message: " .. commandEvent.getArgs()[1])
end)
```


# Gui

With this guide you will be able to create any inventory for your plugin

* [Create a simple inv](https://docs.lukkit.net/gui/gui_simple_inv)
* [Create an advanced inv](https://docs.lukkit.net/gui/gui_advanced_inv)
* [Run function if an inventory item has been clicked](https://docs.lukkit.net/gui/gui_inventory_click)


# Create a simple inv

## Create a simple inventar

```lua
-- Create inventory
local title = "This is the inventory title"
local slots = 9
local inv = plugin.getServer():createInventory(nil, slots, title)
-- Open inventory for player
player:openInventory(inv)
```

**Make sure thah your slots number can be divided by 9 and is lower then 55 (max. Slots 54)**

![inv\_simple](https://user-images.githubusercontent.com/15909166/119182458-39e13d00-ba73-11eb-94eb-b8825194c3ea.png)

## Set an item for the inventory

```lua
-- Import utils
local itemStack = import("org.bukkit.inventory.ItemStack")
local material = import("$.Material")
-- Create inventory
local title = "This is the inventory title"
local slots = 9
local inv = plugin.getServer():createInventory(nil, slots, title)

-- Create new item stack
local countOfItems = 1
local newItemStack = luajava.new(itemStack, material.GRASS, countOfItems, 0)
-- Set item to a slot
local setSlot = 0
inv:setItem(setSlot, newItemStack)
-- Open inventory for player
player:openInventory(inv)
```

This code allows you to open an inventory with an grass block item in the first slot of the inventory

![inv\_with\_item](https://user-images.githubusercontent.com/15909166/119182479-41084b00-ba73-11eb-9f1c-9ad84fcd8984.PNG)


# Create an advanced inv

## Create an item with more information

```lua
-- Import utils
local itemStack = import("org.bukkit.inventory.ItemStack")
local javaArrayList = import("java.util.ArrayList")
local material = import("$.Material")
-- Create inventory
local title = "This is the inventory title"
local slots = 9
local inv = plugin.getServer():createInventory(nil, slots, title)

-- Create new item stack
local countOfItems = 1
local newItemStack = luajava.new(itemStack, material.GRASS, countOfItems, 0)
-- Get item meta from new item stack
local meta = newItemStack:getItemMeta()
-- Set new item text
meta:setDisplayName("WoW crazy item")

-- Set new lore to item
local description = {"WoW this is a cool", "description O.o"}
local list = luajava.new(javaArrayList)
for i = 1, #description do
  list:add(description[i])
end
meta:setLore(list)

-- Set the new item meta
newItemStack:setItemMeta(meta)
-- Set item to a slot
local setSlot = 0
inv:setItem(setSlot, newItemStack)
-- Open inventory for player
player:openInventory(inv)
```

This code allows you to set the item name and the lore text

![inv\_advanced](https://user-images.githubusercontent.com/15909166/119182420-29c95d80-ba73-11eb-8ad8-0ba5825f917c.png)


# Run function if an inventory item has been clicked

## Run a function if an inventory item has been clicked

```lua
plugin.registerEvent("InventoryClickEvent", function(e)
  -- Get info
  local player = e:getWhoClicked()
  local inventoryName = e:getView():getTitle()

  -- Test if the clicked slot is not empty
  if e:getCurrentItem() then
     if e:getCurrentItem():getItemMeta() then
        if e:getCurrentItem():getItemMeta():getDisplayName() then
           -- Get item text
           local clickedItemName = e:getCurrentItem():getItemMeta():getDisplayName()
           -- Test if open inv has contains the name
           if string.find(inventoryName, "This is the inventory title") then
              if string.find(clickedItemName, "WoW crazy item") then
                  -- Here comes your code if the generated item with this name is clicked
              end
              -- Disable dragging or dropping item to this inv
              e:setCancelled(true)
           end
        end
     end
  end
end)
```

You need to register the event *InventoryClickEvent* with [`plugin.registerEvent(event: string, callback: function)`](https://docs.lukkit.net/globals/global-variables/plugin) to test the clicked item in inventory


# Events

Lukkit allows you to hook into events, such as those when a block has been placed or a player has sent a chat message. To register an event, you can use the [`plugin.registerEvent(event: string, callback: function)`](https://docs.lukkit.net/globals/global-variables/plugin) method. The event parameter can be an event listed in the [event list](https://docs.lukkit.net/events/event-list) or a path to a class, such as `org.bukkit.player.PlayerJoinEvent`.


# Examples

This method hooks into the `BlockBreakEvent` event and sends a message to the player who broke the block.

```lua
plugin.registerEvent("BlockBreakEvent", function(e)
    e:getPlayer():sendMessage("You broke a block")
end)
```

This next example allows the player to execute the command `/inspect` in order to be placed into a table. Once placed in this table, the player will not be able to break blocks and instead will receive information on the block that was broken. The same command can be run again to disable this feature.

```lua
-- Imports
material = import("$.Material")
color = newInstance("#.wrappers.ChatColorWrapper", {plugin.getPlugin()})

-- An inspect command with an event to tell what a block is
inspecters = {}

-- Add the command
local inspectCommand = plugin.addCommand({name="inspect"}, function(cmd)
    local sender = cmd.getSender()
    -- Make sure it's a player sending the command
    if not cmd.isPlayerSender() then
        sender:sendMessage(color.DARK_RED:toString() .. "Only players can run this command!")
        return
    end
    -- Go through every inspector and check if any equals this players uuid
    for k,v in pairs(inspecters) do
      if v == sender:getUniqueId() then
            -- Remove them from inspectors and tell them
            table.remove(inspecters, k)
            sender:sendMessage(color.YELLOW .. "You are no longer an inspector")
            return
        end
    end
    -- Else, add them and tell them
    table.insert(inspecters, sender:getUniqueId())
    sender:sendMessage(color.YELLOW .. "You are now an inspector")
end)

-- Add the event
plugin.registerEvent("BlockBreakEvent", function(e)
    -- Go through every inspector and check if any equals this players uuid
    for _,v in pairs(inspecters) do
      if v == e:getPlayer():getUniqueId() then
            -- Tell them the block
            e:getPlayer():sendMessage(color.AQUA .. "That is " .. color.GOLD .. e:getBlock():getType():name())
            e:setCancelled(true)
            break
      end
    end
end)
```


# Event List

The following is a list of all events available in the current Minecraft release. The current release we support right now is 1.12.2.


# Block

Events related to block updates or world interaction.

| Event                    | Description                                                                                                                                   |
| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- |
| BlockBreakEvent          | Called when a block is broken by a player.                                                                                                    |
| BlockBurnEvent           | Called when a block is destroyed as a result of being burnt by fire.                                                                          |
| BlockCanBuildEvent       | Called when we try to place a block, to see if we can build it here or not.                                                                   |
| BlockDamageEvent         | Called when a block is damaged by a player.                                                                                                   |
| BlockDispenseEvent       | Called when an item is dispensed from a block.                                                                                                |
| BlockEvent               | Represents a block related event.                                                                                                             |
| BlockExpEvent            | An event that's called when a block yields experience.                                                                                        |
| BlockExplodeEvent        | Called when a block explodes                                                                                                                  |
| BlockFadeEvent           | Called when a block fades, melts or disappears based on world conditions                                                                      |
| BlockFormEvent           | Called when a block is formed or spreads based on world conditions.                                                                           |
| BlockFromToEvent         | Represents events with a source block and a destination block, currently only applies to liquid (lava and water) and teleporting dragon eggs. |
| BlockGrowEvent           | Called when a block grows naturally in the world.                                                                                             |
| BlockIgniteEvent         | Called when a block is ignited.                                                                                                               |
| BlockMultiPlaceEvent     | Fired when a single block placement action of a player triggers the creation of multiple blocks(e.g.                                          |
| BlockPhysicsEvent        | Thrown when a block physics check is called                                                                                                   |
| BlockPistonEvent         | Called when a piston block is triggered                                                                                                       |
| BlockPistonExtendEvent   | Called when a piston extends                                                                                                                  |
| BlockPistonRetractEvent  | Called when a piston retracts                                                                                                                 |
| BlockPlaceEvent          | Called when a block is placed by a player.                                                                                                    |
| BlockRedstoneEvent       | Called when a redstone current changes                                                                                                        |
| BlockSpreadEvent         | Called when a block spreads based on world conditions.                                                                                        |
| CauldronLevelChangeEvent | Called when the water level in a cauldron changes                                                                                             |
| EntityBlockFormEvent     | Called when a block is formed by entities.                                                                                                    |
| LeavesDecayEvent         | Called when leaves are decaying naturally.                                                                                                    |
| NotePlayEvent            | Called when a note block is being played through player interaction or a redstone current.                                                    |
| SignChangeEvent          | Called when a sign is changed by a player.                                                                                                    |


# Enchantment


# Entity

Events related to enetities, excluding some that reference entities in a more specific manner.

| Event                         | Description                                                                                           |
| ----------------------------- | ----------------------------------------------------------------------------------------------------- |
| AreaEffectCloudApplyEvent     | Called when a lingering potion applies it's effects.                                                  |
| CreatureSpawnEvent            | Called when a creature is spawned into a world.                                                       |
| CreeperPowerEvent             | Called when a Creeper is struck by lightning.                                                         |
| EnderDragonChangePhaseEvent   | Called when an EnderDragon switches controller phase.                                                 |
| EntityAirChangeEvent          | Called when the amount of air an entity has remaining changes.                                        |
| EntityBreakDoorEvent          | Called when an Entity breaks a door                                                                   |
| EntityBreedEvent              | Called when one Entity breeds with another Entity.                                                    |
| EntityChangeBlockEvent        | Called when any Entity, excluding players, changes a block.                                           |
| EntityCombustByBlockEvent     | Called when a block causes an entity to combust.                                                      |
| EntityCombustByEntityEvent    | Called when an entity causes another entity to combust.                                               |
| EntityCombustEvent            | Called when an entity combusts.                                                                       |
| EntityCreatePortalEvent       | Thrown when a Living Entity creates a portal in a world.                                              |
| EntityDamageByBlockEvent      | Called when an entity is damaged by a block                                                           |
| EntityDamageByEntityEvent     | Called when an entity is damaged by an entity                                                         |
| EntityDamageEvent             | Stores data for damage events                                                                         |
| EntityDeathEvent              | Thrown whenever a LivingEntity dies                                                                   |
| EntityEvent                   | Represents an Entity-related event                                                                    |
| EntityExplodeEvent            | Called when an entity explodes                                                                        |
| EntityInteractEvent           | Called when an entity interacts with an object                                                        |
| EntityPickupItemEvent         | Thrown when a entity picks an item up from the ground                                                 |
| EntityPortalEnterEvent        | Called when an entity comes into contact with a portal                                                |
| EntityPortalEvent             | Called when a non-player entity is about to teleport because it is in contact with a portal.          |
| EntityPortalExitEvent         | Called before an entity exits a portal.                                                               |
| EntityRegainHealthEvent       | Stores data for health-regain events                                                                  |
| EntityResurrectEvent          | Called when an entity dies and may have the opportunity to be resurrected.                            |
| EntityShootBowEvent           | Called when a LivingEntity shoots a bow firing an arrow                                               |
| EntityTameEvent               | Thrown when a LivingEntity is tamed                                                                   |
| EntityTargetEvent             | Called when a creature targets or untargets another entity                                            |
| EntityTargetLivingEntityEvent | Called when an Entity targets a LivingEntity and can only target LivingEntity's.                      |
| EntityTeleportEvent           | Thrown when a non-player entity (such as an Enderman) tries to teleport from one location to another. |
| EntityToggleGlideEvent        | Sent when an entity's gliding status is toggled with an Elytra.                                       |
| EntityUnleashEvent            | Called immediately prior to an entity being unleashed.                                                |
| ExpBottleEvent                | Called when a ThrownExpBottle hits and releases experience.                                           |
| ExplosionPrimeEvent           | Called when an entity has made a decision to explode.                                                 |
| FireworkExplodeEvent          | Called when a firework explodes.                                                                      |
| FoodLevelChangeEvent          | Called when a human entity's food level changes                                                       |
| HorseJumpEvent                | Called when a horse jumps.                                                                            |
| ItemDespawnEvent              | This event is called when a Item is removed from the world because it has existed for 5 minutes.      |
| ItemMergeEvent                |                                                                                                       |
| ItemSpawnEvent                | Called when an item is spawned into a world                                                           |
| LingeringPotionSplashEvent    | Called when a splash potion hits an area                                                              |
| PigZapEvent                   | Stores data for pigs being zapped                                                                     |
| PlayerDeathEvent              | Thrown whenever a Player dies                                                                         |
| PlayerLeashEntityEvent        | Called immediately prior to a creature being leashed by a player.                                     |
| PotionSplashEvent             | Called when a splash potion hits an area                                                              |
| ProjectileHitEvent            | Called when a projectile hits an object                                                               |
| ProjectileLaunchEvent         | Called when a projectile is launched.                                                                 |
| SheepDyeWoolEvent             | Called when a sheep's wool is dyed                                                                    |
| SheepRegrowWoolEvent          | Called when a sheep regrows its wool                                                                  |
| SlimeSplitEvent               | Called when a Slime splits into smaller Slimes upon death                                             |
| VillagerAcquireTradeEvent     | Called whenever a villager acquires a new trade.                                                      |
| VillagerReplenishTradeEvent   | Called when a villager's trade's maximum uses is increased, due to a player's trade.                  |


# Hanging

Events for entities that hang.

| Event                     | Description                                             |
| ------------------------- | ------------------------------------------------------- |
| HangingBreakByEntityEvent | Triggered when a hanging entity is removed by an entity |
| HangingBreakEvent         | Triggered when a hanging entity is removed              |
| HangingEvent              | Represents a hanging entity-related event.              |
| HangingPlaceEvent         | Triggered when a hanging entity is created in the world |


# Inventory

Events regarding the manipulation of inventories.

| Event                    | Description                                                                                                                                                                         |
| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| BrewEvent                | Called when the brewing of the contents inside the Brewing Stand is complete.                                                                                                       |
| BrewingStandFuelEvent    | Called when an ItemStack is about to increase the fuel level of a brewing stand.                                                                                                    |
| CraftItemEvent           | Called when the recipe of an Item is completed inside a crafting matrix.                                                                                                            |
| FurnaceBurnEvent         | Called when an ItemStack is successfully burned as fuel in a furnace.                                                                                                               |
| FurnaceExtractEvent      | This event is called when a player takes items out of the furnace                                                                                                                   |
| FurnaceSmeltEvent        | Called when an ItemStack is successfully smelted in a furnace.                                                                                                                      |
| InventoryClickEvent      | This event is called when a player clicks a slot in an inventory.                                                                                                                   |
| InventoryCloseEvent      | Represents a player related inventory event                                                                                                                                         |
| InventoryCreativeEvent   | This event is called when a player in creative mode puts down or picks up an item in their inventory / hotbar and when they drop items from their Inventory while in creative mode. |
| InventoryDragEvent       | This event is called when the player drags an item in their cursor across the inventory.                                                                                            |
| InventoryEvent           | Represents a player related inventory event                                                                                                                                         |
| InventoryInteractEvent   | An abstract base class for events that describe an interaction between a HumanEntity and the contents of an Inventory.                                                              |
| InventoryMoveItemEvent   | Called when some entity or block (e.g.                                                                                                                                              |
| InventoryOpenEvent       | Represents a player related inventory event                                                                                                                                         |
| InventoryPickupItemEvent | Called when a hopper or hopper minecart picks up a dropped item.                                                                                                                    |
| PrepareAnvilEvent        | Called when an item is put in a slot for repair by an anvil.                                                                                                                        |
| PrepareItemCraftEvent    |                                                                                                                                                                                     |


# Player

Events for players.

| Event                                       | Description                                                                                                                                            |
| ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| AsyncPlayerChatEvent                        | This event will sometimes fire synchronously, depending on how it was triggered.                                                                       |
| AsyncPlayerPreLoginEvent                    | Stores details for players attempting to log in.                                                                                                       |
| PlayerAchievementAwardedEvent    Deprecated | future versions of Minecraft do not have achievements                                                                                                  |
| PlayerAdvancementDoneEvent                  | Called when a player has completed all criteria in an advancement.                                                                                     |
| PlayerAnimationEvent                        | Represents a player animation event                                                                                                                    |
| PlayerArmorStandManipulateEvent             | Called when a player interacts with an armor stand and will either swap, retrieve or place an item.                                                    |
| PlayerBedEnterEvent                         | This event is fired when the player is almost about to enter the bed.                                                                                  |
| PlayerBedLeaveEvent                         | This event is fired when the player is leaving a bed.                                                                                                  |
| PlayerBucketEmptyEvent                      | Called when a player empties a bucket                                                                                                                  |
| PlayerBucketEvent                           | Called when a player interacts with a Bucket                                                                                                           |
| PlayerBucketFillEvent                       | Called when a player fills a bucket                                                                                                                    |
| PlayerChangedMainHandEvent                  | Called when a player changes their main hand in the client settings.                                                                                   |
| PlayerChangedWorldEvent                     | Called when a player switches to another world.                                                                                                        |
| PlayerChannelEvent                          | This event is called after a player registers or unregisters a new plugin channel.                                                                     |
| PlayerChatEvent                             | Deprecated. This event will fire from the main thread and allows the use of all of the Bukkit API, unlike the AsyncPlayerChatEvent.                    |
| PlayerChatTabCompleteEvent                  | Called when a player attempts to tab-complete a chat message.                                                                                          |
| PlayerCommandPreprocessEvent                | This event is called whenever a player runs a command (by placing a slash at the start of their message).                                              |
| PlayerDropItemEvent                         | Thrown when a player drops an item from their inventory                                                                                                |
| PlayerEditBookEvent                         | Called when a player edits or signs a book and quill item.                                                                                             |
| PlayerEggThrowEvent                         | Called when a player throws an egg and it might hatch                                                                                                  |
| PlayerEvent                                 | Represents a player related event                                                                                                                      |
| PlayerExpChangeEvent                        | Called when a players experience changes naturally                                                                                                     |
| PlayerFishEvent                             | Thrown when a player is fishing                                                                                                                        |
| PlayerGameModeChangeEvent                   | Called when the GameMode of the player is changed.                                                                                                     |
| PlayerInteractAtEntityEvent                 | Represents an event that is called when a player right clicks an entity that also contains the location where the entity was clicked.                  |
| PlayerInteractEntityEvent                   | Represents an event that is called when a player right clicks an entity.                                                                               |
| PlayerInteractEvent                         | Represents an event that is called when a player interacts with an object or air, potentially fired once for each hand.                                |
| PlayerItemBreakEvent                        | Fired when a player's item breaks (such as a shovel or flint and steel).                                                                               |
| PlayerItemConsumeEvent                      | This event will fire when a player is finishing consuming an item (food, potion, milk bucket).                                                         |
| PlayerItemHeldEvent                         | Fired when a player changes their currently held item                                                                                                  |
| PlayerItemMendEvent                         | Represents when a player has an item repaired via the Mending enchantment.                                                                             |
| PlayerJoinEvent                             | Called when a player joins a server                                                                                                                    |
| PlayerKickEvent                             | Called when a player gets kicked from the server                                                                                                       |
| PlayerLevelChangeEvent                      | Called when a players level changes                                                                                                                    |
| PlayerLocaleChangeEvent                     | Called when a player changes their locale in the client settings.                                                                                      |
| PlayerLoginEvent                            | Stores details for players attempting to log in                                                                                                        |
| PlayerMoveEvent                             | Holds information for player movement events                                                                                                           |
| PlayerPickupArrowEvent                      | Thrown when a player picks up an arrow from the ground.                                                                                                |
| PlayerPickupItemEvent                       | Deprecated. Use EntityPickupItemEvent                                                                                                                  |
| PlayerPortalEvent                           | Called when a player is about to teleport because it is in contact with a portal.                                                                      |
| PlayerPreLoginEvent                         | Deprecated. This event causes synchronization from the login thread; AsyncPlayerPreLoginEvent is preferred to keep the secondary threads asynchronous. |
| PlayerQuitEvent                             | Called when a player leaves a server                                                                                                                   |
| PlayerRegisterChannelEvent                  | This is called immediately after a player registers for a plugin channel.                                                                              |
| PlayerResourcePackStatusEvent               | Called when a player takes action on a resource pack request sent via Player.setResourcePack(java.lang.String).                                        |
| PlayerRespawnEvent                          | Called when a player respawns.                                                                                                                         |
| PlayerShearEntityEvent                      | Called when a player shears an entity                                                                                                                  |
| PlayerStatisticIncrementEvent               | Called when a player statistic is incremented.                                                                                                         |
| PlayerSwapHandItemsEvent                    | Called when a player swap items between main hand and off hand using the hotkey.                                                                       |
| PlayerTeleportEvent                         | Holds information for player teleport events                                                                                                           |
| PlayerToggleFlightEvent                     | Called when a player toggles their flying state                                                                                                        |
| PlayerToggleSneakEvent                      | Called when a player toggles their sneaking state                                                                                                      |
| PlayerToggleSprintEvent                     | Called when a player toggles their sprinting state                                                                                                     |
| PlayerUnleashEntityEvent                    | Called prior to an entity being unleashed due to a player's action.                                                                                    |
| PlayerUnregisterChannelEvent                | This is called immediately after a player unregisters for a plugin channel.                                                                            |
| PlayerVelocityEvent                         | Called when the velocity of a player changes.                                                                                                          |


# Server

Events related to programmatic state changes via the server.

| Event                    | Description                                                                                                |
| ------------------------ | ---------------------------------------------------------------------------------------------------------- |
| BroadcastMessageEvent    | Event triggered for server broadcast messages such as from `plugin.getServer():broadcast(String, String)`. |
| MapInitializeEvent       | Called when a map is initialized.                                                                          |
| PluginDisableEvent       | Called when a plugin is disabled.                                                                          |
| PluginEnableEvent        | Called when a plugin is enabled.                                                                           |
| PluginEvent              | Used for plugin enable and disable events                                                                  |
| RemoteServerCommandEvent | This event is called when a command is received over RCON.                                                 |
| ServerCommandEvent       | This event is called when a command is run by a non-player.                                                |
| ServerEvent              | Miscellaneous server events                                                                                |
| ServerListPingEvent      | Called when a server list ping is coming in.                                                               |
| ServiceEvent             | An event relating to a registered service.                                                                 |
| ServiceRegisterEvent     | This event is called when a service is registered.                                                         |
| ServiceUnregisterEvent   | This event is called when a service is unregistered.                                                       |
| TabCompleteEvent         | Called when a CommandSender of any description (ie: player or console) attempts to tab complete.           |


# Vehicle

Events for vehicular entities.

| Event                       | Description                                                                                      |
| --------------------------- | ------------------------------------------------------------------------------------------------ |
| VehicleBlockCollisionEvent  | Raised when a vehicle collides with a block.                                                     |
| VehicleCollisionEvent       | Raised when a vehicle collides.                                                                  |
| VehicleCreateEvent          | Raised when a vehicle is created.                                                                |
| VehicleDamageEvent          | Raised when a vehicle receives damage.                                                           |
| VehicleDestroyEvent         | Raised when a vehicle is destroyed, which could be caused by either a player or the environment. |
| VehicleEnterEvent           | Raised when an entity enters a vehicle.                                                          |
| VehicleEntityCollisionEvent | Raised when a vehicle collides with an entity.                                                   |
| VehicleEvent                | Represents a vehicle-related event.                                                              |
| VehicleExitEvent            | Raised when a living entity exits a vehicle.                                                     |
| VehicleMoveEvent            | Raised when a vehicle moves.                                                                     |
| VehicleUpdateEvent          | Called when a vehicle updates                                                                    |


# Weather

Events for the weather.

| Event                | Description                                       |
| -------------------- | ------------------------------------------------- |
| LightningStrikeEvent | Stores data for lightning striking                |
| ThunderChangeEvent   | Stores data for thunder state changing in a world |
| WeatherChangeEvent   | Stores data for weather changing in a world       |
| WeatherEvent         | Represents a Weather-related event                |


# World

Events that are triggered through changes to the world.

| Event              | Description                                                                                                                                  |
| ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- |
| ChunkEvent         | Represents a Chunk related event                                                                                                             |
| ChunkLoadEvent     | Called when a chunk is loaded                                                                                                                |
| ChunkPopulateEvent | Thrown when a new chunk has finished being populated.                                                                                        |
| ChunkUnloadEvent   | Called when a chunk is unloaded                                                                                                              |
| PortalCreateEvent  | Called when a portal is created                                                                                                              |
| SpawnChangeEvent   | An event that is called when a world's spawn changes.                                                                                        |
| StructureGrowEvent | Event that is called when an organic structure attempts to grow (Sapling -> Tree), (Mushroom -> Huge Mushroom), naturally or using bonemeal. |
| WorldEvent         | Represents events within a world                                                                                                             |
| WorldInitEvent     | Called when a World is initializing                                                                                                          |
| WorldLoadEvent     | Called when a World is loaded                                                                                                                |
| WorldSaveEvent     | Called when a World is saved.                                                                                                                |
| WorldUnloadEvent   | Called when a World is unloaded                                                                                                              |


# Globals

Globals are resources that can be accessed at all times from anywhere inside of your plugin. These resources can be variables or functions and allow you to control and manipulate your plugin through access to the Bukkit or Spigot API.


# Global Functions

Functions for importing Lua modules and creating new instances also allow the use of various placeholders that can cut down on development time and create an organized environment. Pound symbols `#` inserted in parameter strings are replaced with `nz.co.jammehcow.lukkit.environment` and dollar signs `$` with `org.bukkit`.

* **`require_local(path: string)` : script**

  Import Lua modules into the current script. This function is the same as the original Lua require method and can be used in that manner. The specified path must be relative to the location of the current Lua script. In the following example, the file extension `.lua` is not necessary for importing modules.

  ```lua
  utils = require 'utils'
  ```
* **`import(class: string)` : static Java class**

  Import an enum or static class from Java into the current script.

  ```lua
  local material = import("$.Material")
  ```
* **`newInstance(class: string, args: array)` : Java object**

  Create a new instance of an object from Java.

  ```lua
  color = newInstance("#.wrappers.ChatColorWrapper", {plugin.getPlugin()})
  plugin.getServer():broadcastMessage(color.GOLD .. "Hello world!")
  ```


# Global Variables


# Plugin

Represented by `plugin`.

* **`plugin.onLoad(callback: function)`**

  Event called when the plugin has been loaded.

  ```lua
  plugin.onLoad(function()
  logger.info("Plugin loaded")
  end)
  ```
* **`plugin.onEnable(callback: function)`**

  Event called when the plugin has been enabled.

  ```lua
  plugin.onEnable(function()
  logger.info("Plugin enabled")
  end)
  ```
* **`plugin.onDisable(callback: function)`**

  Event called when the plugin has been disabled.

  ```lua
  plugin.onDisable(function()
  logger.info("Plugin disabled")
  end)
  ```
* **`plugin.addCommand(options: table, callback: function)` :** [**Command**](https://github.com/artex-development/docs.lukkit.net/tree/b600fc95db6df12a29cf3c019492ca125cee8319/globals/global-variables/Commands/README.md#command)

  Create a command. More information on creating commands can be found [here](/commands).

  ```lua
  local testCommand = plugin.addCommand({name="hello",description="Hello world"}, function(cmd)
    plugin.getServer():broadcastMessage("Hello, world!")
  end)
  ```
* **`plugin.registerEvent(event: string, callback: function)`**

  Register an event. More information on registering events can be found [here](/events).

  ```lua
  plugin.registerEvent("BlockBreakEvent", function(e)
    e:getPlayer():sendMessage("You broke a break")
  end)
  ```
* **`plugin.getServer()` :** [**org.bukkit.Server**](https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/Server.html)

  Returns the server object. This is equivalent to `Bukkit.getServer()` in Java.

  ```lua
  local server = plugin.getServer()
  ```
* **`plugin.isNaggable()` : boolean**

  Returns true if the plugin can nag to the log or false otherwise.

  ```lua
  if plugin.isNaggable() then
    logger.info("Plugin is naggable")
  end
  ```
* **`plugin.setNaggable(nag: boolean)`**

  Set the nagging state.

  ```lua
  plugin.setNaggable(true)
  ```
* **`plugin.exportResource(path: string, replace: boolean)`:**

  Export a resource from inside of the plugin workspace to the plugin's data folder.
* **`plugin.getStorageObject(file: string)` :** [**StorageObject**](https://github.com/artex-development/docs.lukkit.net/tree/b600fc95db6df12a29cf3c019492ca125cee8319/globals/global-variables/Storage/README.md#storageobject)

  Read a YAML or JSON storage file. More information and examples on storage files can be found [here](https://github.com/artex-development/docs.lukkit.net/tree/b600fc95db6df12a29cf3c019492ca125cee8319/globals/global-variables/Storage/README.md).


# Logging

Represented by `logger`.

* **`logger.info(msg: string)`**

  Log information to the console at the info level.

  ```lua
  logger.info("Message")
  ```
* **`logger.warn(msg: string)`**

  Log information to the console at the warning level.

  ```lua
  logger.warn("Message")
  ```
* **`logger.severe(msg: string)`**

  Log information to the console at the severe level.

  ```lua
  logger.severe("Message")
  ```
* **`logger.debug(msg: string)`**

  Log information to the console at the debug level.

  ```lua
  logger.debug("Message")
  ```


# Utilities

Represented by `util`.

* **`util.getTableFromList(list: java.util.Collection | java.util.stream.Stream)` : table**

  Convert from a stream or collection in Java to a table in Lua.
* **`util.getTableFromArray(array: array)` : table**

  Convert from a array in Java to a table in Lua.
* **`util.getTableFromMap(map: java.util.Map)` : table**

  Convert from a map in Java to a table in Lua.
* **`util.getTableLength(table: table)` : int**

  Returns the amount of keys available in a table.
* **`util.runAsync(func: function, delay: int)`**

  Run an asynchronous function after a certain time in milliseconds.
* **`util.runDelayed(func: function, delay: int)`**

  Run a synchronous function after a certain time in milliseconds.
* **`util.getClass(class: string)` : java.lang.Class**

  Grab a class from Java using the package and name. (ie `java.io.File`)
* **`util.getSkullMeta(item: org.bukkit.inventory.ItemStack)` :** [**SkullWrapper**](https://github.com/artex-development/docs.lukkit.net/tree/9cfd55fd81df8d045428f2ce1c6a2bcf7bc208eb/globals/global-variables/Wrappers/README.md#Skull)

  Returns the SkullMeta from an ItemStack.
* **`util.getBannerMeta(item: org.bukkit.inventory.ItemStack)` :** [**BannerWrapper**](https://github.com/artex-development/docs.lukkit.net/tree/9cfd55fd81df8d045428f2ce1c6a2bcf7bc208eb/globals/global-variables/Wrappers/README.md#Banner)

  Returns the BennerMeta from an ItemStack.
* **`util.parseItemStack(item: org.bukkit.inventory.ItemStack)` :** [**ItemStackWrapper**](https://github.com/artex-development/docs.lukkit.net/tree/9cfd55fd81df8d045428f2ce1c6a2bcf7bc208eb/globals/global-variables/Wrappers/README.md#ItemStack)

  Convert the userdata from an ItemStack into a table.


# Wrappers


# Examples


# Discord Webhooks (http)

This cool little plugin sends a POST request to a Discord webhook and allow users to send a message to a channel. Some things that could be added or changed would be to send all chat messages to discord, prevent users from using `@everyone` or mentioning users, and running it async so it doesn't slow down the server.

## Code

{% code title="main.lua" %}

```lua
-- Imports
unirest = import("com.mashape.unirest.http.Unirest")
color = newInstance("#.wrappers.ChatColorWrapper", {plugin.getPlugin()})

webhookUrl = "https://discordapp.com/api/webhooks/532360268223741952/1XLKZg9o3a93AMui2BauKUY7SPTWYe2ec_D9gf2UFEvuJ09L8OHJcSXf4j6HoD7j1Cq5"

local discordCommand = plugin.addCommand({name="discord", permission="lukkit.command.discord"}, function(cmd)
    -- Convert arguments into a single string
    argString = ''
    for i, arg in ipairs(cmd:getArgs()) do
        argString = argString .. arg
    end

    -- Make POST request
    response = unirest:post(webhookUrl):field("username", cmd:getSender():getName()):field("content", argString):asString()

    -- Tell user
    cmd.getSender():sendMessage(color.GREEN .. 'Message sent!')
end)

```

{% endcode %}


# Toggle Fly

This plugin allows users with the permission node `lukkit.command.fly` to fly when they run the `/fly` command. The plugin starts off by importing the chat color wrapper so that it can use colors in messages. Then it creates the fly command. In the command, it first checks if the sender is a player because only players are able to fly, then checks if they are already flying. If so then fly is turned off, otherwise, it is turned on. More info is explained in the code.

## Code

{% tabs %}
{% tab title="main.lua" %}

```lua
-- Imports
color = newInstance("#.wrappers.ChatColorWrapper", {plugin.getPlugin()})

-- A simple fly command
local flyCommand = plugin.addCommand({name="fly", permission="lukkit.command.fly"}, function(cmd)
    local sender = cmd.getSender()
    -- Make sure it's a player sending the command
    if not cmd.isPlayerSender() then
        sender:sendMessage(color.DARK_RED .. "Only players can fly, silly!")
        return
    end

    -- If the player is flying the make them fly, otherwise make them fall
    if sender:isFlying() then
        sender:setFlying(false)
        sender:setAllowFlight(false)
        sender:sendMessage(color.RED .. "Fly off")
    else
        -- This allows the player to fly
        sender:setAllowFlight(true)
        sender:setFlying(true)
        -- The player won't fly if it is on the ground, so we need to move them up a little
        sender:teleport(sender:getLocation():add(0, 0.000001, 0))
        sender:sendMessage(color.GREEN .. "Fly on")
    end
end)
```

{% endtab %}

{% tab title="plugin.yml" %}

```yaml
name: Fly-Plugin
author: AL_1
version: "1.3"
description: A plugin to let players fly!
main: main.lua
```

{% endtab %}
{% endtabs %}


# Hello, world!

This plugin is very simple. When the plugin loads "Hello, world" is printed to the console. This is a example is great to use as a template.

## Code

{% tabs %}
{% tab title="main.lua" %}

```lua
plugin.onEnable(function()
  logger.info("Hello, world!")
end)

plugin.onDisable(function()
  logger.info("Goodbye, world!")
end)
```

{% endtab %}

{% tab title="plugin.yml" %}

```yaml
name: Hello-World
author: AL_1
version: "1.0"
description: Just here to say hello
main: main.lua
```

{% endtab %}
{% endtabs %}


