Files
.github
src
.gitignore
.tool-versions
build.gradle.kts
gradle.properties
LICENSE
README.md
renovate.json
settings.gradle.kts
Code
22 2,117
src/main/kotlin/win/templeos/computers/lua/LuaManager.kt
package win.templeos.computers.lua
import org.bukkit.Bukkit
import org.bukkit.scheduler.BukkitRunnable
import party.iroiro.luajava.JFunction
import party.iroiro.luajava.Lua
import party.iroiro.luajava.lua54.Lua54
import party.iroiro.luajava.luajit.LuaJit
import party.iroiro.luajava.luajit.LuaJitConsts
import party.iroiro.luajava.value.LuaValue
import win.templeos.computers.Computers
import win.templeos.computers.config.LuaRuntimes
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.nio.ByteBuffer
import java.nio.charset.StandardCharsets
import java.util.stream.Collectors
class LuaManager(private val plugin: Computers, luaRuntime: LuaRuntimes) {
// Create a new Lua state
private val lua: Lua = try {
when (luaRuntime) {
LuaRuntimes.LUAJIT -> {
plugin.logger.info("Initializing LuaJIT")
LuaJit()
}
LuaRuntimes.LUA54 -> {
plugin.logger.info("Initializing Lua 5.4")
Lua54()
}
else -> {
throw UnsupportedOperationException("Configured runtime is not LuaJIT or Lua 5.4")
}
}
} catch (e: UnsatisfiedLinkError) {
plugin.logger.warning("LuaJIT failed to load due to missing dependencies (likely libgcc). Falling back to Lua 5.4.")
Lua54()
} catch (e: UnsupportedOperationException) {
Lua54()
}
private var scriptManagerTable: LuaValue? = null
// Path to the Lua script in resources
companion object {
private const val LUA_SCRIPT_MANAGER_PATH = "/lua/scriptmanager.lua"
private const val LUA_SCRIPT_CLASS_PATH = "/lua/script.lua"
private const val LUA_SCRIPT_PATH = "/lua/computers.lua"
private const val LUA_SCRIPT_SCHEDULER_PATH = "/lua/scheduler.lua"
}
/**
* Creates a new ScriptManager
*/
init {
lua.openLibrary("string")
lua.openLibrary("table")
lua.openLibrary("math")
lua.openLibrary("os")
lua.openLibrary("io")
lua.openLibrary("package")
lua.openLibrary("debug")
lua.pushJavaObject(Bukkit.getServer())
lua.setGlobal("server")
lua.pushJavaObject(plugin)
lua.setGlobal("__plugin")
lua.push(JFunction {
// Possibly a bad solution? Possibly not?
if (!it.isString(1)) {
it.error("Script name is null")
return@JFunction 0
}
if (!it.isString(2)) {
it.error("Command name is null")
return@JFunction 0
}
val scriptName: String? = it.toString(1)
val commandName: String? = it.toString(2)
if (scriptName == null) {
it.error("Script name is null")
return@JFunction 0
}
if (commandName == null) {
it.error("Command name is null")
return@JFunction 0
}
if (scriptManagerTable == null) {
it.error("ScriptManager table is null")
return@JFunction 0
}
val commands = scriptManagerTable!!.get("getVariable").call(scriptName, "script.commands")[0]
if (commands?.size == 0) {
it.error("Commands table is null")
return@JFunction 0
}
val commandData = commands?.get(commandName)
if (commandData == null) {
it.error("Command data is null")
return@JFunction 0
}
val command = LuaCommand(commandData!!)
plugin.server.commandMap.register("computersscript", command)
return@JFunction 0
})
lua.setGlobal("__registerCommand")
lua.push(JFunction {
val scriptsDir = this.plugin.dataFolder.resolve("scripts")
if (!scriptsDir.exists()) {
scriptsDir.mkdirs()
}
// Get all subdirectories in the scripts directory that contain a main.lua file
val scriptFolders = scriptsDir.listFiles()?.filter { it.isDirectory && it.resolve("main.lua").exists() }
// Create a table to hold the script names
lua.newTable()
// Iterate through the script folders and add their names to the table
scriptFolders?.forEachIndexed { index, folder ->
val scriptName = folder.name
lua.push(index + 1) // Push the key (1-based index for Lua arrays)
lua.push(scriptName) // Push the value
lua.setTable(-3) // Set table[-3][index+1] = scriptName
}
return@JFunction 1
})
lua.setGlobal("__getAvailableScripts")
lua.push(JFunction {
Bukkit.getServer().javaClass.getMethod("syncCommands").invoke(Bukkit.getServer())
return@JFunction 0
})
lua.setGlobal("__syncCommands")
lua.push(JFunction { it ->
// The first argument is a Lua function
if (!it.isFunction(-2)) {
it.error("Expected a function as the first argument")
return@JFunction 0
}
// The second argument is a boolean indicating if it should be unrefed after execution
val shouldUnref = if (it.isBoolean(-1)) it.toBoolean(-1) else false
// Create a reference to the function at stack position 1
it.pushValue(-2) // Duplicate the function on the stack
val ref = it.ref() // Store in registry and get reference
val runnable: BukkitRunnable = object : BukkitRunnable() {
override fun run() {
synchronized(lua.mainState) {
// Get the Lua function from the registry using the reference
it.refGet(ref)
// Push this runnable as the first argument
it.pushJavaObject(this)
// Call the function with pcall (1 arg, 0 returns)
it.pCall(1, 0)
if (shouldUnref) {
it.unref(ref)
}
}
}
// Clean up the reference when the runnable is cancelled/finished
override fun cancel() {
super.cancel()
it.unref(ref)
}
}
// Push the runnable as the return value
it.pushJavaObject(runnable)
// Push the reference as the second return value
it.push(ref)
return@JFunction 2
})
lua.setGlobal("__createRunnable")
// Create a function to ref stuff. Mainly used to ensure references to tasks are kept alive
lua.push(JFunction { it ->
if (!it.isFunction(-1)) {
it.error("Expected a function as the first argument")
return@JFunction 0
}
it.pushValue(-1)
val ref = it.ref()