JS: Improve REPL script

This commit is contained in:
Willy-JL
2024-10-17 21:32:31 +01:00
parent 908461a3c2
commit 685e06b4d6

View File

@@ -11,8 +11,9 @@ storage.makeDirectory("/ext/.tmp/js");
storage.rmrf("/ext/.tmp/js/repl")
storage.makeDirectory("/ext/.tmp/js/repl")
let ctx = {
tmp_template: "/ext/.tmp/js/repl/",
tmp_number: 0,
tmpTemplate: "/ext/.tmp/js/repl/",
tmpNumber: 0,
persistentScope: {},
};
let views = {
@@ -41,28 +42,40 @@ eventLoop.subscribe(views.dialog.input, function (_sub, button, gui, views) {
eventLoop.subscribe(views.textInput.input, function (_sub, text, gui, views, ctx) {
gui.viewDispatcher.switchTo(views.loading);
let path = ctx.tmp_template + toString(ctx.tmp_number++);
let path = ctx.tmpTemplate + toString(ctx.tmpNumber++);
let file = storage.openFile(path, "w", "create_always");
file.write("({run:function(){return " + text + ";},})");
file.write(text);
file.close();
// Hide GUI before running, we want to see console and avoid deadlock if code fails
gui.viewDispatcher.sendTo("back");
let result = load(path).run();
let result = load(path, ctx.persistentScope); // Load runs JS and returns last value on stack
storage.remove(path);
gui.viewDispatcher.sendTo("front");
// Must convert to string explicitly
if (typeof result === "number") {
if (result === null) { // mJS: typeof null === "null", ECMAScript: typeof null === "object", IDE complains when checking "null" type
result = "null";
} else if (typeof result === "string") {
result = "'" + result + "'";
} else if (typeof result === "number") {
result = toString(result);
} else if (typeof result === "undefined") {
result = "undefined";
} else if (typeof result === "bigint") { // mJS doesn't support BigInt() but might aswell check
result = "bigint";
} else if (typeof result === "boolean") {
result = result ? "true" : "false";
} else if (typeof result === "symbol") { // mJS doesn't support Symbol() but might aswell check
result = "symbol";
} else if (typeof result === "undefined") {
result = "undefined";
} else if (typeof result === "object") {
result = JSON.stringify(result);
result = "object"; // JSON.stringify() is not implemented
} else if (typeof result === "function") {
result = "function";
} else {
result = "unknown type: " + typeof result;
}
gui.viewDispatcher.sendTo("front");
views.dialog.set("header", "JS Returned:");
views.dialog.set("text", result);
gui.viewDispatcher.switchTo(views.dialog);
@@ -74,4 +87,8 @@ eventLoop.subscribe(gui.viewDispatcher.navigation, function (_sub, _, eventLoop)
}, eventLoop);
gui.viewDispatcher.switchTo(views.dialog);
// Message behind GUI if something breaks
print("If you're stuck here, something went wrong, re-run the script")
eventLoop.run();
print("\n\nFinished correctly :)")