aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--README.md4
-rw-r--r--src/lauxlib.js2
-rw-r--r--src/loadlib.js18
3 files changed, 22 insertions, 2 deletions
diff --git a/README.md b/README.md
index 7cb3ef6..4ce66c7 100644
--- a/README.md
+++ b/README.md
@@ -22,6 +22,10 @@ Lua strings are 8-bits clean and can embed `\0`. Which means that invalid UTF-8/
To address that issue, Lua strings are represented by an array of bytes in Fengari. To push a JS string on the stack you can use `lua_pushliteral` which will convert it to an array of bytes before pushing it. To get a Lua string on the stack as a JS string you can use `lua_tojsstring` which will attempt to convert it to a UTF-16 JS string. The latter won't give you what you expect if the Lua string is not a valid UTF-16 sequence. You can also convert strings with `lua.to_luastring` and `lua.to_jsstring`.
+### `require` and `package.loadlib`
+
+In the browser `require` and `package.loadlib` try to find a file by making XHR requests.
+
### _Missing_ features
- `lua_gc`/`collectgarbage`: Fengari relies on the JS garbage collector and does not implement its own.
diff --git a/src/lauxlib.js b/src/lauxlib.js
index d13b2bb..eb174be 100644
--- a/src/lauxlib.js
+++ b/src/lauxlib.js
@@ -816,7 +816,7 @@ if (!WEB) {
lf.f = lua.to_luastring(xhr.response);
} else {
lf.err = xhr.status;
- return errfile(L, "open", fnameindex, xhr.status);
+ return errfile(L, "open", fnameindex, { message: `${xhr.status}: ${xhr.statusText}` });
}
}
let com = skipcomment(lf);
diff --git a/src/loadlib.js b/src/loadlib.js
index e448381..9400bb0 100644
--- a/src/loadlib.js
+++ b/src/loadlib.js
@@ -34,7 +34,7 @@ const AUXMARK = [1];
** Returns the library; in case of error, returns NULL plus an
** error string in the stack.
*/
-const lsys_load = function(L, path) {
+let lsys_load = function(L, path) {
try {
path = lua.to_jsstring(path);
@@ -65,6 +65,22 @@ const lsys_sym = function(L, lib, sym) {
}
};
+if (WEB) {
+ lsys_load = function(L, path) {
+ let xhr = new XMLHttpRequest();
+ xhr.open("GET", lua.to_jsstring(path), false);
+ xhr.send();
+ /* TODO: subresource integrity check? */
+
+ if (xhr.status === 200) {
+ return eval(xhr.response);
+ } else {
+ lua.lua_pushstring(L, lua.to_luastring(`${xhr.status}: ${xhr.statusText}`));
+ return null;
+ }
+ };
+}
+
/*
** return registry.LUA_NOENV as a boolean
*/