馃搨 SourceLoader
SourceLoader to interfejs kt贸ry m贸wi silnikowi KitsuneScript jak i sk膮d 艂adowa膰 importowane pliki 藕r贸d艂owe.
Po co SourceLoader?
Gdy w skrypcie u偶ywasz instrukcji import "file.ks" in alias;, silnik musi wiedzie膰 sk膮d wzi膮膰 kod tego pliku. SourceLoader definiuje t臋 logik臋 - mo偶e 艂adowa膰 pliki z assets, systemu plik贸w, sieci, bazy danych itp.
Interfejs
fun interface SourceLoader {
fun load(path: String): String?
}
Konfiguracja silnika
val engine = KitsuneScriptEngine.builder()
.withSourceLoader(myLoader)
.build()
Przyk艂ady implementacji
艁adowanie z Android Assets
val assetLoader = SourceLoader { path ->
try {
context.assets.open(path)
.bufferedReader()
.use { it.readText() }
} catch (e: Exception) {
null
}
}
val engine = KitsuneScriptEngine.builder()
.withSourceLoader(assetLoader)
.build()
艁adowanie z systemu plik贸w
import java.io.File
val fileLoader = SourceLoader { path ->
val baseDir = File("/data/scripts/")
val file = File(baseDir, path)
if (file.exists() && file.isFile) {
file.readText()
} else {
null
}
}
艁adowanie z zasob贸w (resources)
val resourceLoader = SourceLoader { path ->
javaClass.classLoader
?.getResourceAsStream("scripts/$path")
?.bufferedReader()
?.use { it.readText() }
}
艁adowanie z mapy (dla test贸w)
val modules = mapOf(
"utils.ks" to """
export fn double(x) { return x * 2; }
export let VERSION = "1.0";
""".trimIndent(),
"math.ks" to """
export fn square(x) { return x * x; }
""".trimIndent()
)
val testLoader = SourceLoader { path -> modules[path] }
Kombinacja 藕r贸de艂
val combinedLoader = SourceLoader { path ->
try {
context.assets.open(path)
.bufferedReader().use { it.readText() }
} catch (e: Exception) {
val localFile = File(context.filesDir, "scripts/$path")
if (localFile.exists()) {
localFile.readText()
} else {
null
}
}
}
U偶ycie w skrypcie
Po skonfigurowaniu SourceLoader, skrypty mog膮 importowa膰 modu艂y:
import "math_utils.ks" in math;
import "string_utils.ks" in str;
log(math.factorial(5));
log(str.capitalize("hello"));
log(math.VERSION);
Bez SourceLoader
Je艣li nie skonfigurujesz SourceLoader, pr贸ba u偶ycia import w skrypcie spowoduje b艂膮d:
import "some_module.ks" in mod;
Cache modu艂贸w
Silnik automatycznie cache'uje za艂adowane modu艂y - ka偶dy plik jest parsowany i wykonywany tylko raz, nawet przy wielokrotnym imporcie.
U偶ycie z KitsuneScriptRunner
KitsuneScriptRunner r贸wnie偶 wspiera SourceLoader przez metod臋 withSourceLoader() lub w艂a艣ciwo艣膰 sourceLoader:
val runner = KitsuneScriptRunner.createInstance("myScript")
.withSourceLoader { path ->
context.assets.open("scripts/$path")
.bufferedReader()
.readText()
}
val runner = KitsuneScriptRunner.createInstance("myScript")
runner.sourceLoader = SourceLoader { path ->
File("/scripts", path).readText()
}
runner.execute("""
import "utils.ks" in utils;
import "helpers.ks" in helpers;
let result = utils.calculate(helpers.getData());
result;
""")