Example Code

This page is a work in progress!

LuaJava Examples

Bind the Bukkit Class

Allows the org.bukkit.Bukkit class to be called directly from Lua. Note: This example requires "unsafe" APIs to be enabled in the config.

-- Bind the class
Bukkit = luajava.bindClass("org.bukkit.Bukkit")

-- Example usages
-- Broadcast a message
Bukkit:broadcastMessage("Hi from LuaJava!")

-- Set a player's fly speed
Bukkit:getPlayer("USERNAME"):setFlySpeed(0.2)

-- Run a command as the console
Bukkit:dispatchCommand(Bukkit:getConsoleSender(), "say Hi!")

-- Disable a plugin, delete its config, then enable it again
local pluginManager = Bukkit:getPluginManager()
if pluginManager:isPluginEnabled("PLUGIN") then
    local randomPlugin = pluginManager:getPlugin("PLUGIN")
    pluginManager:disablePlugin(randomPlugin)
    luajava.newInstance("java.io.File", randomPlugin:getDataFolder(), "config.yml"):delete()
    pluginManager:enablePlugin(randomPlugin)
end

Bind the System Class

Allows the java.lang.System class to be called directly from Lua. Note: This example requires "unsafe" APIs to be enabled in the config.

System = luajava.bindClass("java.lang.System")

-- Example usages
System.out:println("Hi!")
System.err:println("NotReallyAnError")
startTime = System:currentTimeMillis()
-- Insert long process here
endTime = System:currentTimeMillis()
info("Long process took " .. tostring(endTime - startTime) .. " milliseconds!")

Create a new File Object

This example creates an instance of java.io.File and uses it to print the number of files in the plugin directory. Note: This example requires "unsafe" APIs to be enabled in the config.

-- Bind needed class
System = luajava.bindClass("java.lang.System")

-- Constants
local workingDir = System:getProperty("user.dir")
local pluginFile = luajava.newInstance("java.io.File", workingDir, "plugins")

-- Print the number of files in the plugins folder
info("Files in the plugins folder: " .. tostring(pluginFile:listFiles().length))

Read a Number from a Web Socket

Opens a socket to a web address, then reads a number from the connection. Note: This example requires "unsafe" APIs to be enabled in the config.

-- Place code in table
local runnableImpl = {}
runnableImpl.run = function()
    -- Constants
    local address = "example.com"
    local port = 5000

    -- Variables
    local socket = nil
    local number = nil
    local ok = nil
    local message = nil

    -- Safely run socket related code with pcall
    ok, message = pcall(function()
        -- Open socket
        socket = luajava.newInstance("java.net.Socket", address, port)
        -- Create input stream
        local input = luajava.newInstance("java.io.DataInputStream", socket:getInputStream())
        -- Read number
        number = input:readInt()
    end)
    if not ok then
        warning(message)
    end

    -- Safely close the socket using pcall
    ok, message = pcall(function()
        -- Close socket
        socket:close()
    end)
    if not ok then
        warning(message)
    end

    -- Print number, or error message
    if number then
        info("The number is " .. tostring(number))
    else
        warning("Failed to read number!")
    end
end

-- Start code in separate thread
luajava.newInstance("java.lang.Thread", luajava.createProxy("java.lang.Runnable", runnableImpl)):start()

Event System Examples

Log When a Player Interacts With the World

Prints a message to the console when a player attempts to interact with the world.

events.onPlayerInteract:add(function(player, action)
    info("Player " .. player:getName() .. " interacted with the world by performing action " .. action .. ".")
end)

Change Death Message Color

Changes the color of death messages to red.

events.onPlayerDeath:add(function(player, message)
    return chatCode("#4" .. message)
end)

Change Chat Message Format

Changes the format of chat messages to "player: message".

events.onPlayerChat:add(function()
    return nil, nil, chatCode("#9%s: #7%s")
end)

Strike Lightning Where a Player Clicks

Strikes lightning at the crosshair of a configurable player when they click.

lightningPlayer = "USERNAME"
events.onPlayerInteract:add(function(player)
    if player:getName() == lightningPlayer then
        x, y, z = player:getTargetBlock(100)
        player:getLocation():lightning(x, y, z, true)
    end
end)