🔌 Host Functions
Host Functions pozwalają skryptom wywoływać kod Kotlin.
Rejestracja funkcji
import rip.nerd.kitsunescript.runtime.HostFunction
engine.register("greet", HostFunction { args, _ ->
val name = args.firstOrNull()?.asString() ?: "World"
Value.Str("Hello, $name!")
})
engine.register("sum", HostFunction { args, _ ->
val total = args.sumOf { it.asNumber() }
Value.Num(total)
})
engine.register("log", HostFunction { args, _ ->
println(args.joinToString(" ") { it.asString() })
Value.Null
})
Dostęp do kontekstu
engine.register("showToast", HostFunction { args, context ->
val message = args.firstOrNull()?.asString() ?: ""
Toast.makeText(activity, message, Toast.LENGTH_SHORT).show()
Value.Null
})
Callback z Kotlin do skryptu
var scriptCallback: Value.FunctionVal? = null
engine.register("setCallback", HostFunction { args, _ ->
scriptCallback = args.firstOrNull() as? Value.FunctionVal
Value.Null
})
fun notifyScript(data: String) {
scriptCallback?.let { callback ->
engine.invokeFunction(callback, listOf(Value.Str(data)))
}
}
Praktyczny przykład: API
engine.register("fetchData", HostFunction { args, _ ->
val url = args.firstOrNull()?.asString() ?: return@HostFunction Value.Null
try {
val response = URL(url).readText()
Value.Str(response)
} catch (e: Exception) {
Value.MapVal(mutableMapOf(
"error" to Value.Str(e.message ?: "Unknown error")
))
}
})