package ru.dbotthepony.kstarbound.lua import ru.dbotthepony.kstarbound.Starbound import java.io.Closeable import java.lang.ref.Cleaner.Cleanable class LuaHandle(private val parent: LuaSharedState, val handle: Int, val key: Any?) : Closeable { private val cleanable: Cleanable var isValid = true private set init { val parent = parent val handle = handle val key = key cleanable = Starbound.CLEANER.register(this) { parent.freeHandle(handle, key) } } fun push(into: LuaThread) { check(isValid) { "Tried to use NULL handle!" } parent.handlesThread.push() parent.handlesThread.copy(handle, -1) parent.handlesThread.moveStackValuesOnto(into) } override fun close() { if (!isValid) return cleanable.clean() isValid = false } }