diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/defs.js | 18 | ||||
| -rw-r--r-- | src/fengari.js | 18 | ||||
| -rw-r--r-- | src/fengaricore.js | 36 | ||||
| -rw-r--r-- | src/lauxlib.js | 93 | ||||
| -rw-r--r-- | src/lbaselib.js | 47 | ||||
| -rw-r--r-- | src/lcorolib.js | 3 | ||||
| -rw-r--r-- | src/ldblib.js | 83 | ||||
| -rw-r--r-- | src/linit.js | 4 | ||||
| -rw-r--r-- | src/liolib.js | 21 | ||||
| -rw-r--r-- | src/lmathlib.js | 21 | ||||
| -rw-r--r-- | src/loadlib.js | 95 | ||||
| -rw-r--r-- | src/loslib.js | 37 | ||||
| -rw-r--r-- | src/lstrlib.js | 133 | ||||
| -rw-r--r-- | src/ltablib.js | 32 | ||||
| -rw-r--r-- | src/lua.js | 14 | ||||
| -rw-r--r-- | src/lutf8lib.js | 29 | 
16 files changed, 359 insertions, 325 deletions
diff --git a/src/defs.js b/src/defs.js index fc18707..c1720c3 100644 --- a/src/defs.js +++ b/src/defs.js @@ -22,16 +22,6 @@ const LUA_RELEASE             = LUA_VERSION + "." + LUA_VERSION_RELEASE;  const LUA_COPYRIGHT           = LUA_RELEASE + "  Copyright (C) 1994-2017 Lua.org, PUC-Rio";  const LUA_AUTHORS             = "R. Ierusalimschy, L. H. de Figueiredo, W. Celes"; -const FENGARI_VERSION_MAJOR   = "0"; -const FENGARI_VERSION_MINOR   = "0"; -const FENGARI_VERSION_NUM     = 1; -const FENGARI_VERSION_RELEASE = "1"; - -const FENGARI_VERSION         = "Fengari " + FENGARI_VERSION_MAJOR + "." + FENGARI_VERSION_MINOR; -const FENGARI_RELEASE         = FENGARI_VERSION + "." + FENGARI_VERSION_RELEASE; -const FENGARI_AUTHORS         = "B. Giannangeli, Daurnimator"; -const FENGARI_COPYRIGHT       = FENGARI_RELEASE + "  Copyright (C) 2017-2018 " + FENGARI_AUTHORS + "\nBased on: " + LUA_COPYRIGHT; -  const LUA_VERSUFFIX           = "_" + LUA_VERSION_MAJOR + "_" + LUA_VERSION_MINOR;  const LUA_INIT_VAR            = "LUA_INIT"; @@ -437,14 +427,6 @@ if (typeof process === "undefined") {  }  module.exports.CT                      = CT; -module.exports.FENGARI_AUTHORS         = FENGARI_AUTHORS; -module.exports.FENGARI_COPYRIGHT       = FENGARI_COPYRIGHT; -module.exports.FENGARI_RELEASE         = FENGARI_RELEASE; -module.exports.FENGARI_VERSION         = FENGARI_VERSION; -module.exports.FENGARI_VERSION_MAJOR   = FENGARI_VERSION_MAJOR; -module.exports.FENGARI_VERSION_MINOR   = FENGARI_VERSION_MINOR; -module.exports.FENGARI_VERSION_NUM     = FENGARI_VERSION_NUM; -module.exports.FENGARI_VERSION_RELEASE = FENGARI_VERSION_RELEASE;  module.exports.LUA_AUTHORS             = LUA_AUTHORS;  module.exports.LUA_COPYRIGHT           = LUA_COPYRIGHT;  module.exports.LUA_HOOKCALL            = LUA_HOOKCALL; diff --git a/src/fengari.js b/src/fengari.js index 3d35334..b37f7d6 100644 --- a/src/fengari.js +++ b/src/fengari.js @@ -1,5 +1,23 @@  "use strict"; +const core = require("./fengaricore.js"); + +module.exports.FENGARI_AUTHORS         = core.FENGARI_AUTHORS; +module.exports.FENGARI_COPYRIGHT       = core.FENGARI_COPYRIGHT; +module.exports.FENGARI_RELEASE         = core.FENGARI_RELEASE; +module.exports.FENGARI_VERSION         = core.FENGARI_VERSION; +module.exports.FENGARI_VERSION_MAJOR   = core.FENGARI_VERSION_MAJOR; +module.exports.FENGARI_VERSION_MINOR   = core.FENGARI_VERSION_MINOR; +module.exports.FENGARI_VERSION_NUM     = core.FENGARI_VERSION_NUM; +module.exports.FENGARI_VERSION_RELEASE = core.FENGARI_VERSION_RELEASE; + +module.exports.luastring_eq      = core.luastring_eq; +module.exports.luastring_indexOf = core.luastring_indexOf; +module.exports.luastring_of      = core.luastring_of; +module.exports.to_jsstring       = core.to_jsstring; +module.exports.to_luastring      = core.to_luastring; +module.exports.to_uristring      = core.to_uristring; +  const lua      = require('./lua.js');  const lauxlib  = require('./lauxlib.js');  const lualib   = require('./lualib.js'); diff --git a/src/fengaricore.js b/src/fengaricore.js new file mode 100644 index 0000000..1fd0354 --- /dev/null +++ b/src/fengaricore.js @@ -0,0 +1,36 @@ +/* Fengari specific functions + * + * This file includes fengari-specific data or and functionality for users to + * manipulate fengari's string type. + * The fields are exposed to the user on the 'fengari' entry point; however to + * avoid a dependency on defs.js from lauxlib.js they are defined in this file. + */ + +const defs = require("./defs.js"); + +const FENGARI_VERSION_MAJOR   = "0"; +const FENGARI_VERSION_MINOR   = "0"; +const FENGARI_VERSION_NUM     = 1; +const FENGARI_VERSION_RELEASE = "1"; +const FENGARI_VERSION         = "Fengari " + FENGARI_VERSION_MAJOR + "." + FENGARI_VERSION_MINOR; +const FENGARI_RELEASE         = FENGARI_VERSION + "." + FENGARI_VERSION_RELEASE; +const FENGARI_AUTHORS         = "B. Giannangeli, Daurnimator"; +const FENGARI_COPYRIGHT       = FENGARI_RELEASE + "  Copyright (C) 2017-2018 " + FENGARI_AUTHORS + "\nBased on: " + defs.LUA_COPYRIGHT; + +module.exports.FENGARI_AUTHORS         = FENGARI_AUTHORS; +module.exports.FENGARI_COPYRIGHT       = FENGARI_COPYRIGHT; +module.exports.FENGARI_RELEASE         = FENGARI_RELEASE; +module.exports.FENGARI_VERSION         = FENGARI_VERSION; +module.exports.FENGARI_VERSION_MAJOR   = FENGARI_VERSION_MAJOR; +module.exports.FENGARI_VERSION_MINOR   = FENGARI_VERSION_MINOR; +module.exports.FENGARI_VERSION_NUM     = FENGARI_VERSION_NUM; +module.exports.FENGARI_VERSION_RELEASE = FENGARI_VERSION_RELEASE; +module.exports.is_luastring            = defs.is_luastring; +module.exports.luastring_eq            = defs.luastring_eq; +module.exports.luastring_from          = defs.luastring_from; +module.exports.luastring_indexOf       = defs.luastring_indexOf; +module.exports.luastring_of            = defs.luastring_of; +module.exports.to_jsstring             = defs.to_jsstring; +module.exports.to_luastring            = defs.to_luastring; +module.exports.to_uristring            = defs.to_uristring; +module.exports.from_userstring         = defs.from_userstring; diff --git a/src/lauxlib.js b/src/lauxlib.js index 52ea3a2..5dc42c2 100644 --- a/src/lauxlib.js +++ b/src/lauxlib.js @@ -1,22 +1,23 @@  "use strict"; -const lua     = require('./lua.js'); +const lua = require('./lua.js'); +const {luastring_eq, to_luastring, to_uristring} = require("./fengaricore.js");  /* extra error code for 'luaL_loadfilex' */  const LUA_ERRFILE = lua.LUA_ERRERR+1;  /* key, in the registry, for table of loaded modules */ -const LUA_LOADED_TABLE = lua.to_luastring("_LOADED"); +const LUA_LOADED_TABLE = to_luastring("_LOADED");  /* key, in the registry, for table of preloaded loaders */ -const LUA_PRELOAD_TABLE = lua.to_luastring("_PRELOAD"); +const LUA_PRELOAD_TABLE = to_luastring("_PRELOAD"); -const LUA_FILEHANDLE = lua.to_luastring("FILE*"); +const LUA_FILEHANDLE = to_luastring("FILE*");  const LUAL_NUMSIZES  = 4*16 + 8; -const __name = lua.to_luastring("__name"); -const __tostring = lua.to_luastring("__tostring"); +const __name = to_luastring("__name"); +const __tostring = to_luastring("__tostring");  const empty = new Uint8Array(0); @@ -65,7 +66,7 @@ const findfield = function(L, objidx, level) {  */  const pushglobalfuncname = function(L, ar) {      let top = lua.lua_gettop(L); -    lua.lua_getinfo(L, lua.to_luastring("f"), ar);  /* push function */ +    lua.lua_getinfo(L, to_luastring("f"), ar);  /* push function */      lua.lua_getfield(L, lua.LUA_REGISTRYINDEX, LUA_LOADED_TABLE);      if (findfield(L, top + 1, 2)) {          let name = lua.lua_tostring(L, -1); @@ -84,15 +85,15 @@ const pushglobalfuncname = function(L, ar) {  const pushfuncname = function(L, ar) {      if (pushglobalfuncname(L, ar)) {  /* try first a global name */ -        lua.lua_pushfstring(L, lua.to_luastring("function '%s'"), lua.lua_tostring(L, -1)); +        lua.lua_pushfstring(L, to_luastring("function '%s'"), lua.lua_tostring(L, -1));          lua.lua_remove(L, -2);  /* remove name */      }      else if (ar.namewhat.length !== 0)  /* is there a name from code? */ -        lua.lua_pushfstring(L, lua.to_luastring("%s '%s'"), ar.namewhat, ar.name);  /* use it */ +        lua.lua_pushfstring(L, to_luastring("%s '%s'"), ar.namewhat, ar.name);  /* use it */      else if (ar.what && ar.what[0] === 'm'.charCodeAt(0))  /* main? */          lua.lua_pushliteral(L, "main chunk");      else if (ar.what && ar.what[0] === 'L'.charCodeAt(0))  /* for Lua functions, use <file:line> */ -        lua.lua_pushfstring(L, lua.to_luastring("function <%s:%d>"), ar.short_src, ar.linedefined); +        lua.lua_pushfstring(L, to_luastring("function <%s:%d>"), ar.short_src, ar.linedefined);      else  /* nothing left... */          lua.lua_pushliteral(L, "?");  }; @@ -118,7 +119,7 @@ const luaL_traceback = function(L, L1, msg, level) {      let last = lastlevel(L1);      let n1 = last - level > LEVELS1 + LEVELS2 ? LEVELS1 : -1;      if (msg) -        lua.lua_pushfstring(L, lua.to_luastring("%s\n"), msg); +        lua.lua_pushfstring(L, to_luastring("%s\n"), msg);      luaL_checkstack(L, 10, null);      lua.lua_pushliteral(L, "stack traceback:");      while (lua.lua_getstack(L1, level++, ar)) { @@ -126,8 +127,8 @@ const luaL_traceback = function(L, L1, msg, level) {              lua.lua_pushliteral(L, "\n\t...");  /* add a '...' */              level = last - LEVELS2 + 1;  /* and skip to last ones */          } else { -            lua.lua_getinfo(L1, lua.to_luastring("Slnt", true), ar); -            lua.lua_pushfstring(L, lua.to_luastring("\n\t%s:"), ar.short_src); +            lua.lua_getinfo(L1, to_luastring("Slnt", true), ar); +            lua.lua_pushfstring(L, to_luastring("\n\t%s:"), ar.short_src);              if (ar.currentline > 0)                  lua.lua_pushliteral(L, `${ar.currentline}:`);              lua.lua_pushliteral(L, " in "); @@ -153,20 +154,20 @@ const luaL_argerror = function(L, arg, extramsg) {      let ar = new lua.lua_Debug();      if (!lua.lua_getstack(L, 0, ar))  /* no stack frame? */ -        return luaL_error(L, lua.to_luastring("bad argument #%d (%s)"), arg, extramsg); +        return luaL_error(L, to_luastring("bad argument #%d (%s)"), arg, extramsg); -    lua.lua_getinfo(L, lua.to_luastring("n"), ar); +    lua.lua_getinfo(L, to_luastring("n"), ar); -    if (lua.luastring_eq(ar.namewhat, lua.to_luastring("method"))) { +    if (luastring_eq(ar.namewhat, to_luastring("method"))) {          arg--;  /* do not count 'self' */          if (arg === 0)  /* error is in the self argument itself? */ -            return luaL_error(L, lua.to_luastring("calling '%s' on bad self (%s)"), ar.name, extramsg); +            return luaL_error(L, to_luastring("calling '%s' on bad self (%s)"), ar.name, extramsg);      }      if (ar.name === null) -        ar.name = pushglobalfuncname(L, ar) ? lua.lua_tostring(L, -1) : lua.to_luastring("?"); +        ar.name = pushglobalfuncname(L, ar) ? lua.lua_tostring(L, -1) : to_luastring("?"); -    return luaL_error(L, lua.to_luastring("bad argument #%d to '%s' (%s)"), arg, ar.name, extramsg); +    return luaL_error(L, to_luastring("bad argument #%d to '%s' (%s)"), arg, ar.name, extramsg);  };  const typeerror = function(L, arg, tname) { @@ -174,24 +175,24 @@ const typeerror = function(L, arg, tname) {      if (luaL_getmetafield(L, arg, __name) === lua.LUA_TSTRING)          typearg = lua.lua_tostring(L, -1);      else if (lua.lua_type(L, arg) === lua.LUA_TLIGHTUSERDATA) -        typearg = lua.to_luastring("light userdata", true); +        typearg = to_luastring("light userdata", true);      else          typearg = luaL_typename(L, arg); -    let msg = lua.lua_pushfstring(L, lua.to_luastring("%s expected, got %s"), tname, typearg); +    let msg = lua.lua_pushfstring(L, to_luastring("%s expected, got %s"), tname, typearg);      return luaL_argerror(L, arg, msg);  };  const luaL_where = function(L, level) {      let ar = new lua.lua_Debug();      if (lua.lua_getstack(L, level, ar)) { -        lua.lua_getinfo(L, lua.to_luastring("Sl", true), ar); +        lua.lua_getinfo(L, to_luastring("Sl", true), ar);          if (ar.currentline > 0) { -            lua.lua_pushfstring(L, lua.to_luastring("%s:%d: "), ar.short_src, ar.currentline); +            lua.lua_pushfstring(L, to_luastring("%s:%d: "), ar.short_src, ar.currentline);              return;          }      } -    lua.lua_pushstring(L, lua.to_luastring("")); +    lua.lua_pushstring(L, to_luastring(""));  };  const luaL_error = function(L, fmt, ...argp) { @@ -209,9 +210,9 @@ const luaL_fileresult = function(L, stat, fname, e) {      } else {          lua.lua_pushnil(L);          if (fname) -            lua.lua_pushfstring(L, lua.to_luastring("%s: %s"), fname, lua.to_luastring(e.message)); +            lua.lua_pushfstring(L, to_luastring("%s: %s"), fname, to_luastring(e.message));          else -            lua.lua_pushstring(L, lua.to_luastring(e.message)); +            lua.lua_pushstring(L, to_luastring(e.message));          lua.lua_pushinteger(L, -e.errno);          return 3;      } @@ -288,7 +289,7 @@ const luaL_checkoption = function(L, arg, def, lst) {      for (let i = 0; lst[i]; i++)          if (lst[i].join('|') === name.join('|'))              return i; -    return luaL_argerror(L, arg, lua.lua_pushfstring(L, lua.to_luastring("invalid option '%s'"), name)); +    return luaL_argerror(L, arg, lua.lua_pushfstring(L, to_luastring("invalid option '%s'"), name));  };  const tag_error = function(L, arg, tag) { @@ -312,7 +313,7 @@ const luaL_argcheck = function(L, cond, arg, extramsg) {  const luaL_checkany = function(L, arg) {      if (lua.lua_type(L, arg) === lua.LUA_TNONE) -        luaL_argerror(L, arg, lua.to_luastring("value expected", true)); +        luaL_argerror(L, arg, to_luastring("value expected", true));  };  const luaL_checktype = function(L, arg, t) { @@ -340,7 +341,7 @@ const luaL_optstring = luaL_optlstring;  const interror = function(L, arg) {      if (lua.lua_isnumber(L, arg)) -        luaL_argerror(L, arg, lua.to_luastring("number has no integer representation", true)); +        luaL_argerror(L, arg, to_luastring("number has no integer representation", true));      else          tag_error(L, arg, lua.LUA_TNUMBER);  }; @@ -489,17 +490,17 @@ const luaL_len = function(L, idx) {      lua.lua_len(L, idx);      let l = lua.lua_tointegerx(L, -1);      if (l === false) -        luaL_error(L, lua.to_luastring("object length is not an integer", true)); +        luaL_error(L, to_luastring("object length is not an integer", true));      lua.lua_pop(L, 1);  /* remove object */      return l;  }; -const p_I = lua.to_luastring("%I"); -const p_f = lua.to_luastring("%f"); +const p_I = to_luastring("%I"); +const p_f = to_luastring("%f");  const luaL_tolstring = function(L, idx) {      if (luaL_callmeta(L, idx, __tostring)) {          if (!lua.lua_isstring(L, -1)) -            luaL_error(L, lua.to_luastring("'__tostring' must return a string")); +            luaL_error(L, to_luastring("'__tostring' must return a string"));      } else {          let t = lua.lua_type(L, idx);          switch(t) { @@ -522,7 +523,7 @@ const luaL_tolstring = function(L, idx) {              default: {                  let tt = luaL_getmetafield(L, idx, __name);                  let kind = tt === lua.LUA_TSTRING ? lua.lua_tostring(L, -1) : luaL_typename(L, idx); -                lua.lua_pushfstring(L, lua.to_luastring("%s: %p"), kind, lua.lua_topointer(L, idx)); +                lua.lua_pushfstring(L, to_luastring("%s: %p"), kind, lua.lua_topointer(L, idx));                  if (tt !== lua.LUA_TNIL)                      lua.lua_remove(L, -2);                  break; @@ -608,12 +609,12 @@ const luaL_getsubtable = function(L, idx, fname) {  ** Returns with only the table at the stack.  */  const luaL_setfuncs = function(L, l, nup) { -    luaL_checkstack(L, nup, lua.to_luastring("too many upvalues", true)); +    luaL_checkstack(L, nup, to_luastring("too many upvalues", true));      for (let lib in l) {  /* fill the table with given functions */          for (let i = 0; i < nup; i++)  /* copy upvalues to the top */              lua.lua_pushvalue(L, -nup);          lua.lua_pushcclosure(L, l[lib], nup);  /* closure with those upvalues */ -        lua.lua_setfield(L, -(nup + 2), lua.to_luastring(lib)); +        lua.lua_setfield(L, -(nup + 2), to_luastring(lib));      }      lua.lua_pop(L, nup);  /* remove upvalues */  }; @@ -628,9 +629,9 @@ const luaL_setfuncs = function(L, l, nup) {  const luaL_checkstack = function(L, space, msg) {      if (!lua.lua_checkstack(L, space)) {          if (msg) -            luaL_error(L, lua.to_luastring("stack overflow (%s)"), msg); +            luaL_error(L, to_luastring("stack overflow (%s)"), msg);          else -            luaL_error(L, lua.to_luastring('stack overflow', true)); +            luaL_error(L, to_luastring('stack overflow', true));      }  }; @@ -682,7 +683,7 @@ const luaL_unref = function(L, t, ref) {  const errfile = function(L, what, fnameindex, error) {      let serr = error.message;      let filename = lua.lua_tostring(L, fnameindex).subarray(1); -    lua.lua_pushfstring(L, lua.to_luastring("cannot %s %s: %s"), lua.to_luastring(what), filename, lua.to_luastring(serr)); +    lua.lua_pushfstring(L, to_luastring("cannot %s %s: %s"), to_luastring(what), filename, to_luastring(serr));      lua.lua_remove(L, fnameindex);      return LUA_ERRFILE;  }; @@ -768,8 +769,8 @@ if (typeof process === "undefined") {          if (filename === null) {              throw new Error("Can't read stdin in the browser");          } else { -            lua.lua_pushfstring(L, lua.to_luastring("@%s"), filename); -            let path = lua.to_uristring(filename); +            lua.lua_pushfstring(L, to_luastring("@%s"), filename); +            let path = to_uristring(filename);              let xhr = new XMLHttpRequest();              xhr.open("GET", path, false);              /* XXX: Synchronous xhr in main thread always returns a js string @@ -781,7 +782,7 @@ if (typeof process === "undefined") {              xhr.send();              if (xhr.status >= 200 && xhr.status <= 299) {                  if (typeof xhr.response === "string") { -                    lf.f = lua.to_luastring(xhr.response); +                    lf.f = to_luastring(xhr.response);                  } else {                      lf.f = new Uint8Array(xhr.response);                  } @@ -851,7 +852,7 @@ if (typeof process === "undefined") {              lua.lua_pushliteral(L, "=stdin");              lf.f = process.stdin.fd;          } else { -            lua.lua_pushfstring(L, lua.to_luastring("@%s"), filename); +            lua.lua_pushfstring(L, to_luastring("@%s"), filename);              try {                  lf.f = fs.openSync(filename, "r");              } catch (e) { @@ -910,11 +911,11 @@ const luaL_checkversion = function(L) {      let sz = LUAL_NUMSIZES;      let v = lua.lua_version(L);      if (sz != LUAL_NUMSIZES)  /* check numeric types */ -        luaL_error(L, lua.to_luastring("core and library have incompatible numeric types")); +        luaL_error(L, to_luastring("core and library have incompatible numeric types"));      if (v != lua.lua_version(null)) -        luaL_error(L, lua.to_luastring("multiple Lua VMs detected")); +        luaL_error(L, to_luastring("multiple Lua VMs detected"));      else if (v !== ver) -        luaL_error(L, lua.to_luastring("version mismatch: app. needs %f, Lua core provides %f"), ver, v); +        luaL_error(L, to_luastring("version mismatch: app. needs %f, Lua core provides %f"), ver, v);  };  module.exports.LUA_ERRFILE          = LUA_ERRFILE; diff --git a/src/lbaselib.js b/src/lbaselib.js index ca03b7f..78a32ed 100644 --- a/src/lbaselib.js +++ b/src/lbaselib.js @@ -2,6 +2,7 @@  const lua     = require('./lua.js');  const lauxlib = require('./lauxlib.js'); +const {to_jsstring, to_luastring} = require("./fengaricore.js");  let lua_writestring;  let lua_writeline; @@ -23,7 +24,7 @@ if (typeof process === "undefined") {          lua_writestring = function(s) {              try {                  /* If the string is valid utf8, then we can use to_jsstring */ -                s = lua.to_jsstring(s); +                s = to_jsstring(s);              } catch(e) {                  /* otherwise push copy of raw array */                  let copy = new Uint8Array(s.length); @@ -47,15 +48,15 @@ if (typeof process === "undefined") {  }  const luaB_print = function(L) {      let n = lua.lua_gettop(L); /* number of arguments */ -    lua.lua_getglobal(L, lua.to_luastring("tostring", true)); +    lua.lua_getglobal(L, to_luastring("tostring", true));      for (let i = 1; i <= n; i++) {          lua.lua_pushvalue(L, -1);  /* function to be called */          lua.lua_pushvalue(L, i);  /* value to print */          lua.lua_call(L, 1, 1);          let s = lua.lua_tolstring(L, -1);          if (s === null) -            return lauxlib.luaL_error(L, lua.to_luastring("'tostring' must return a string to 'print'", true)); -        if (i > 1) lua_writestring(lua.to_luastring("\t")); +            return lauxlib.luaL_error(L, to_luastring("'tostring' must return a string to 'print'", true)); +        if (i > 1) lua_writestring(to_luastring("\t"));          lua_writestring(s);          lua.lua_pop(L, 1);      } @@ -76,16 +77,16 @@ const luaB_getmetatable = function(L) {          lua.lua_pushnil(L);          return 1;  /* no metatable */      } -    lauxlib.luaL_getmetafield(L, 1, lua.to_luastring("__metatable", true)); +    lauxlib.luaL_getmetafield(L, 1, to_luastring("__metatable", true));      return 1;  /* returns either __metatable field (if present) or metatable */  };  const luaB_setmetatable = function(L) {      let t = lua.lua_type(L, 2);      lauxlib.luaL_checktype(L, 1, lua.LUA_TTABLE); -    lauxlib.luaL_argcheck(L, t === lua.LUA_TNIL || t === lua.LUA_TTABLE, 2, lua.to_luastring("nil or table expected", true)); -    if (lauxlib.luaL_getmetafield(L, 1, lua.to_luastring("__metatable", true)) !== lua.LUA_TNIL) -        return lauxlib.luaL_error(L, lua.to_luastring("cannot change a protected metatable", true)); +    lauxlib.luaL_argcheck(L, t === lua.LUA_TNIL || t === lua.LUA_TTABLE, 2, to_luastring("nil or table expected", true)); +    if (lauxlib.luaL_getmetafield(L, 1, to_luastring("__metatable", true)) !== lua.LUA_TNIL) +        return lauxlib.luaL_error(L, to_luastring("cannot change a protected metatable", true));      lua.lua_settop(L, 2);      lua.lua_setmetatable(L, 1);      return 1; @@ -100,7 +101,7 @@ const luaB_rawequal = function(L) {  const luaB_rawlen = function(L) {      let t = lua.lua_type(L, 1); -    lauxlib.luaL_argcheck(L, t === lua.LUA_TTABLE || t === lua.LUA_TSTRING, 1, lua.to_luastring("table or string expected", true)); +    lauxlib.luaL_argcheck(L, t === lua.LUA_TTABLE || t === lua.LUA_TSTRING, 1, to_luastring("table or string expected", true));      lua.lua_pushinteger(L, lua.lua_rawlen(L, 1));      return 1;  }; @@ -126,16 +127,16 @@ const opts = [      "stop", "restart", "collect",      "count", "step", "setpause", "setstepmul",      "isrunning" -].map((e) => lua.to_luastring(e)); +].map((e) => to_luastring(e));  const luaB_collectgarbage = function(L) { -    lauxlib.luaL_checkoption(L, 1, lua.to_luastring("collect"), opts); +    lauxlib.luaL_checkoption(L, 1, to_luastring("collect"), opts);      lauxlib.luaL_optinteger(L, 2, 0); -    lauxlib.luaL_error(L, lua.to_luastring("lua_gc not implemented")); +    lauxlib.luaL_error(L, to_luastring("lua_gc not implemented"));  };  const luaB_type = function(L) {      let t = lua.lua_type(L, 1); -    lauxlib.luaL_argcheck(L, t !== lua.LUA_TNONE, 1, lua.to_luastring("value expected", true)); +    lauxlib.luaL_argcheck(L, t !== lua.LUA_TNONE, 1, to_luastring("value expected", true));      lua.lua_pushstring(L, lua.lua_typename(L, t));      return 1;  }; @@ -166,7 +167,7 @@ const luaB_next = function(L) {  };  const luaB_pairs = function(L) { -    return pairsmeta(L, lua.to_luastring("__pairs", true), 0, luaB_next); +    return pairsmeta(L, to_luastring("__pairs", true), 0, luaB_next);  };  /* @@ -195,7 +196,7 @@ const luaB_ipairs = function(L) {  const b_str2int = function(s, base) {      try { -        s = lua.to_jsstring(s); +        s = to_jsstring(s);      } catch (e) {          return null;      } @@ -229,7 +230,7 @@ const luaB_tonumber = function(L) {          let base = lauxlib.luaL_checkinteger(L, 2);          lauxlib.luaL_checktype(L, 1, lua.LUA_TSTRING);  /* no numbers as strings */          let s = lua.lua_tostring(L, 1); -        lauxlib.luaL_argcheck(L, 2 <= base && base <= 36, 2, lua.to_luastring("base out of range", true)); +        lauxlib.luaL_argcheck(L, 2 <= base && base <= 36, 2, to_luastring("base out of range", true));          let n = b_str2int(s, base);          if (n !== null) {              lua.lua_pushinteger(L, n); @@ -273,7 +274,7 @@ const luaB_select = function(L) {          let i = lauxlib.luaL_checkinteger(L, 1);          if (i < 0) i = n + i;          else if (i > n) i = n; -        lauxlib.luaL_argcheck(L, 1 <= i, 1, lua.to_luastring("index out of range", true)); +        lauxlib.luaL_argcheck(L, 1 <= i, 1, to_luastring("index out of range", true));          return n - i;      }  }; @@ -347,28 +348,28 @@ const RESERVEDSLOT = 5;  ** reserved slot inside the stack.  */  const generic_reader = function(L, ud) { -    lauxlib.luaL_checkstack(L, 2, lua.to_luastring("too many nested functions", true)); +    lauxlib.luaL_checkstack(L, 2, to_luastring("too many nested functions", true));      lua.lua_pushvalue(L, 1);  /* get function */      lua.lua_call(L, 0, 1);  /* call it */      if (lua.lua_isnil(L, -1)) {          lua.lua_pop(L, 1);  /* pop result */          return null;      } else if (!lua.lua_isstring(L, -1)) -        lauxlib.luaL_error(L, lua.to_luastring("reader function must return a string", true)); +        lauxlib.luaL_error(L, to_luastring("reader function must return a string", true));      lua.lua_replace(L, RESERVEDSLOT);  /* save string in reserved slot */      return lua.lua_tostring(L, RESERVEDSLOT);  };  const luaB_load = function(L) {      let s = lua.lua_tostring(L, 1); -    let mode = lauxlib.luaL_optstring(L, 3, lua.to_luastring("bt", true)); +    let mode = lauxlib.luaL_optstring(L, 3, to_luastring("bt", true));      let env = !lua.lua_isnone(L, 4) ? 4 : 0;  /* 'env' index or 0 if no 'env' */      let status;      if (s !== null) {  /* loading a string? */          let chunkname = lauxlib.luaL_optstring(L, 2, s);          status = lauxlib.luaL_loadbufferx(L, s, s.length, chunkname, mode);      } else {  /* loading from a reader function */ -        let chunkname = lauxlib.luaL_optstring(L, 2, lua.to_luastring("=(load)", true)); +        let chunkname = lauxlib.luaL_optstring(L, 2, to_luastring("=(load)", true));          lauxlib.luaL_checktype(L, 1, lua.LUA_TFUNCTION);          lua.lua_settop(L, RESERVEDSLOT);  /* create reserved slot */          status = lua.lua_load(L, generic_reader, null, chunkname, mode); @@ -428,10 +429,10 @@ const luaopen_base = function(L) {      lauxlib.luaL_setfuncs(L, base_funcs, 0);      /* set global _G */      lua.lua_pushvalue(L, -1); -    lua.lua_setfield(L, -2, lua.to_luastring("_G", true)); +    lua.lua_setfield(L, -2, to_luastring("_G", true));      /* set global _VERSION */      lua.lua_pushliteral(L, lua.LUA_VERSION); -    lua.lua_setfield(L, -2, lua.to_luastring("_VERSION", true)); +    lua.lua_setfield(L, -2, to_luastring("_VERSION", true));      return 1;  }; diff --git a/src/lcorolib.js b/src/lcorolib.js index a72d22b..bcdae8b 100644 --- a/src/lcorolib.js +++ b/src/lcorolib.js @@ -2,10 +2,11 @@  const lua     = require('./lua.js');  const lauxlib = require('./lauxlib.js'); +const {to_luastring} = require("./fengaricore.js");  const getco = function(L) {      let co = lua.lua_tothread(L, 1); -    lauxlib.luaL_argcheck(L, co, 1, lua.to_luastring("thread expected", true)); +    lauxlib.luaL_argcheck(L, co, 1, to_luastring("thread expected", true));      return co;  }; diff --git a/src/ldblib.js b/src/ldblib.js index 7e08dc5..9698f7a 100644 --- a/src/ldblib.js +++ b/src/ldblib.js @@ -4,6 +4,7 @@ const assert  = require('assert');  const lua     = require('./lua.js');  const lauxlib = require('./lauxlib.js'); +const {luastring_indexOf, to_luastring} = require("./fengaricore.js");  /*  ** If L1 != L, L1 can be in any state, and therefore there are no @@ -12,7 +13,7 @@ const lauxlib = require('./lauxlib.js');  */  const checkstack = function(L, L1, n) {      if (L !== L1 && !lua.lua_checkstack(L1, n)) -        lauxlib.luaL_error(L, lua.to_luastring("stack overflow", true)); +        lauxlib.luaL_error(L, to_luastring("stack overflow", true));  };  const db_getregistry = function(L) { @@ -30,7 +31,7 @@ const db_getmetatable = function(L) {  const db_setmetatable = function(L) {      const t = lua.lua_type(L, 2); -    lauxlib.luaL_argcheck(L, t == lua.LUA_TNIL || t == lua.LUA_TTABLE, 2, lua.to_luastring("nil or table expected", true)); +    lauxlib.luaL_argcheck(L, t == lua.LUA_TNIL || t == lua.LUA_TTABLE, 2, to_luastring("nil or table expected", true));      lua.lua_settop(L, 2);      lua.lua_setmetatable(L, 1);      return 1;  /* return 1st argument */ @@ -120,10 +121,10 @@ const db_getinfo = function(L) {      let thread = getthread(L);      let arg = thread.arg;      let L1 = thread.thread; -    let options = lauxlib.luaL_optstring(L, arg + 2, lua.to_luastring("flnStu", true)); +    let options = lauxlib.luaL_optstring(L, arg + 2, to_luastring("flnStu", true));      checkstack(L, L1, 3);      if (lua.lua_isfunction(L, arg + 1)) {  /* info about a function? */ -        options = lua.lua_pushfstring(L, lua.to_luastring(">%s"), options);  /* add '>' to 'options' */ +        options = lua.lua_pushfstring(L, to_luastring(">%s"), options);  /* add '>' to 'options' */          lua.lua_pushvalue(L, arg + 1);  /* move function to 'L1' stack */          lua.lua_xmove(L, L1, 1);      } else {  /* stack level */ @@ -134,32 +135,32 @@ const db_getinfo = function(L) {      }      if (!lua.lua_getinfo(L1, options, ar)) -        lauxlib.luaL_argerror(L, arg + 2, lua.to_luastring("invalid option", true)); +        lauxlib.luaL_argerror(L, arg + 2, to_luastring("invalid option", true));      lua.lua_newtable(L);  /* table to collect results */ -    if (lua.luastring_indexOf(options, 'S'.charCodeAt(0)) > -1) { -        settabss(L, lua.to_luastring("source", true), ar.source); -        settabss(L, lua.to_luastring("short_src", true), ar.short_src); -        settabsi(L, lua.to_luastring("linedefined", true), ar.linedefined); -        settabsi(L, lua.to_luastring("lastlinedefined", true), ar.lastlinedefined); -        settabss(L, lua.to_luastring("what", true), ar.what); +    if (luastring_indexOf(options, 'S'.charCodeAt(0)) > -1) { +        settabss(L, to_luastring("source", true), ar.source); +        settabss(L, to_luastring("short_src", true), ar.short_src); +        settabsi(L, to_luastring("linedefined", true), ar.linedefined); +        settabsi(L, to_luastring("lastlinedefined", true), ar.lastlinedefined); +        settabss(L, to_luastring("what", true), ar.what);      } -    if (lua.luastring_indexOf(options, 'l'.charCodeAt(0)) > -1) -        settabsi(L, lua.to_luastring("currentline", true), ar.currentline); -    if (lua.luastring_indexOf(options, 'u'.charCodeAt(0)) > -1) { -        settabsi(L, lua.to_luastring("nups", true), ar.nups); -        settabsi(L, lua.to_luastring("nparams", true), ar.nparams); -        settabsb(L, lua.to_luastring("isvararg", true), ar.isvararg); +    if (luastring_indexOf(options, 'l'.charCodeAt(0)) > -1) +        settabsi(L, to_luastring("currentline", true), ar.currentline); +    if (luastring_indexOf(options, 'u'.charCodeAt(0)) > -1) { +        settabsi(L, to_luastring("nups", true), ar.nups); +        settabsi(L, to_luastring("nparams", true), ar.nparams); +        settabsb(L, to_luastring("isvararg", true), ar.isvararg);      } -    if (lua.luastring_indexOf(options, 'n'.charCodeAt(0)) > -1) { -        settabss(L, lua.to_luastring("name", true), ar.name); -        settabss(L, lua.to_luastring("namewhat", true), ar.namewhat); +    if (luastring_indexOf(options, 'n'.charCodeAt(0)) > -1) { +        settabss(L, to_luastring("name", true), ar.name); +        settabss(L, to_luastring("namewhat", true), ar.namewhat);      } -    if (lua.luastring_indexOf(options, 't'.charCodeAt(0)) > -1) -        settabsb(L, lua.to_luastring("istailcall", true), ar.istailcall); -    if (lua.luastring_indexOf(options, 'L'.charCodeAt(0)) > -1) -        treatstackoption(L, L1, lua.to_luastring("activelines", true)); -    if (lua.luastring_indexOf(options, 'f'.charCodeAt(0)) > -1) -        treatstackoption(L, L1, lua.to_luastring("func", true)); +    if (luastring_indexOf(options, 't'.charCodeAt(0)) > -1) +        settabsb(L, to_luastring("istailcall", true), ar.istailcall); +    if (luastring_indexOf(options, 'L'.charCodeAt(0)) > -1) +        treatstackoption(L, L1, to_luastring("activelines", true)); +    if (luastring_indexOf(options, 'f'.charCodeAt(0)) > -1) +        treatstackoption(L, L1, to_luastring("func", true));      return 1;  /* return table */  }; @@ -176,7 +177,7 @@ const db_getlocal = function(L) {      } else {  /* stack-level argument */          let level = lauxlib.luaL_checkinteger(L, arg + 1);          if (!lua.lua_getstack(L1, level, ar))  /* out of range? */ -            return lauxlib.luaL_argerror(L, arg+1, lua.to_luastring("level out of range", true)); +            return lauxlib.luaL_argerror(L, arg+1, to_luastring("level out of range", true));          checkstack(L, L1, 1);          let name = lua.lua_getlocal(L1, ar, nvar);          if (name) { @@ -200,7 +201,7 @@ const db_setlocal = function(L) {      let level = lauxlib.luaL_checkinteger(L, arg + 1);      let nvar = lauxlib.luaL_checkinteger(L, arg + 2);      if (!lua.lua_getstack(L1, level, ar))  /* out of range? */ -        return lauxlib.luaL_argerror(L, arg + 1, lua.to_luastring("level out of range", true)); +        return lauxlib.luaL_argerror(L, arg + 1, to_luastring("level out of range", true));      lauxlib.luaL_checkany(L, arg + 3);      lua.lua_settop(L, arg + 3);      checkstack(L, L1, 1); @@ -242,7 +243,7 @@ const db_setupvalue = function(L) {  const checkupval = function(L, argf, argnup) {      let nup = lauxlib.luaL_checkinteger(L, argnup);  /* upvalue index */      lauxlib.luaL_checktype(L, argf, lua.LUA_TFUNCTION);  /* closure */ -    lauxlib.luaL_argcheck(L, (lua.lua_getupvalue(L, argf, nup) !== null), argnup, lua.to_luastring("invalid upvalue index", true)); +    lauxlib.luaL_argcheck(L, (lua.lua_getupvalue(L, argf, nup) !== null), argnup, to_luastring("invalid upvalue index", true));      return nup;  }; @@ -255,8 +256,8 @@ const db_upvalueid = function(L) {  const db_upvaluejoin = function(L) {      let n1 = checkupval(L, 1, 2);      let n2 = checkupval(L, 3, 4); -    lauxlib.luaL_argcheck(L, !lua.lua_iscfunction(L, 1), 1, lua.to_luastring("Lua function expected", true)); -    lauxlib.luaL_argcheck(L, !lua.lua_iscfunction(L, 3), 3, lua.to_luastring("Lua function expected", true)); +    lauxlib.luaL_argcheck(L, !lua.lua_iscfunction(L, 1), 1, to_luastring("Lua function expected", true)); +    lauxlib.luaL_argcheck(L, !lua.lua_iscfunction(L, 3), 3, to_luastring("Lua function expected", true));      lua.lua_upvaluejoin(L, 1, n1, 3, n2);      return 0;  }; @@ -265,9 +266,9 @@ const db_upvaluejoin = function(L) {  ** The hook table at registry[HOOKKEY] maps threads to their current  ** hook function. (We only need the unique address of 'HOOKKEY'.)  */ -const HOOKKEY = lua.to_luastring("__hooks__", true); +const HOOKKEY = to_luastring("__hooks__", true); -const hooknames = ["call", "return", "line", "count", "tail call"].map(e => lua.to_luastring(e)); +const hooknames = ["call", "return", "line", "count", "tail call"].map(e => to_luastring(e));  /*  ** Call hook function registered at hook table for the current @@ -281,7 +282,7 @@ const hookf = function(L, ar) {          if (ar.currentline >= 0)              lua.lua_pushinteger(L, ar.currentline);  /* push current line */          else lua.lua_pushnil(L); -        assert(lua.lua_getinfo(L, lua.to_luastring("lS"), ar)); +        assert(lua.lua_getinfo(L, to_luastring("lS"), ar));          lua.lua_call(L, 2, 0);  /* call hook function */      }  }; @@ -291,9 +292,9 @@ const hookf = function(L, ar) {  */  const makemask = function(smask, count) {      let mask = 0; -    if (lua.luastring_indexOf(smask, "c".charCodeAt(0)) > -1) mask |= lua.LUA_MASKCALL; -    if (lua.luastring_indexOf(smask, "r".charCodeAt(0)) > -1) mask |= lua.LUA_MASKRET; -    if (lua.luastring_indexOf(smask, "l".charCodeAt(0)) > -1) mask |= lua.LUA_MASKLINE; +    if (luastring_indexOf(smask, "c".charCodeAt(0)) > -1) mask |= lua.LUA_MASKCALL; +    if (luastring_indexOf(smask, "r".charCodeAt(0)) > -1) mask |= lua.LUA_MASKRET; +    if (luastring_indexOf(smask, "l".charCodeAt(0)) > -1) mask |= lua.LUA_MASKLINE;      if (count > 0) mask |= lua.LUA_MASKCOUNT;      return mask;  }; @@ -328,8 +329,8 @@ const db_sethook = function(L) {          lua.lua_createtable(L, 0, 2);  /* create a hook table */          lua.lua_pushvalue(L, -1);          lua.lua_rawsetp(L, lua.LUA_REGISTRYINDEX, HOOKKEY);  /* set it in position */ -        lua.lua_pushstring(L, lua.to_luastring("k")); -        lua.lua_setfield(L, -2, lua.to_luastring("__mode", true));  /** hooktable.__mode = "k" */ +        lua.lua_pushstring(L, to_luastring("k")); +        lua.lua_setfield(L, -2, to_luastring("__mode", true));  /** hooktable.__mode = "k" */          lua.lua_pushvalue(L, -1);          lua.lua_setmetatable(L, -2);  /* setmetatable(hooktable) = hooktable */      } @@ -424,8 +425,8 @@ if (getinput) {              if (input.length === 0)                  continue; -            let buffer = lua.to_luastring(input); -            if (lauxlib.luaL_loadbuffer(L, buffer, buffer.length, lua.to_luastring("=(debug command)", true)) +            let buffer = to_luastring(input); +            if (lauxlib.luaL_loadbuffer(L, buffer, buffer.length, to_luastring("=(debug command)", true))                  || lua.lua_pcall(L, 0, 0, 0)) {                  lauxlib.lua_writestringerror(lua.lua_tojsstring(L, -1), "\n");              } diff --git a/src/linit.js b/src/linit.js index 97cbfc9..5656bae 100644 --- a/src/linit.js +++ b/src/linit.js @@ -2,6 +2,8 @@  const lua      = require('./lua.js');  const lauxlib  = require('./lauxlib.js'); +const {to_luastring} = require("./fengaricore.js"); +  const lbaselib = require('./lbaselib.js');  const lcorolib = require('./lcorolib.js');  const lmathlib = require('./lmathlib.js'); @@ -30,7 +32,7 @@ const luaL_openlibs = function(L) {      /* "require" functions from 'loadedlibs' and set results to global table */      for (let lib in loadedlibs) { -        lauxlib.luaL_requiref(L, lua.to_luastring(lib), loadedlibs[lib], 1); +        lauxlib.luaL_requiref(L, to_luastring(lib), loadedlibs[lib], 1);          lua.lua_pop(L, 1); /* remove lib */      }  }; diff --git a/src/liolib.js b/src/liolib.js index 66ef3db..462e7ed 100644 --- a/src/liolib.js +++ b/src/liolib.js @@ -5,11 +5,12 @@ const fs      = require('fs');  const lua     = require('./lua.js');  const lauxlib = require('./lauxlib.js'); +const {to_luastring} = require("./fengaricore.js");  const IO_PREFIX = "_IO_";  const IOPREF_LEN = IO_PREFIX.length; -const IO_INPUT = lua.to_luastring(IO_PREFIX + "input"); -const IO_OUTPUT = lua.to_luastring(IO_PREFIX + "output"); +const IO_INPUT = to_luastring(IO_PREFIX + "input"); +const IO_OUTPUT = to_luastring(IO_PREFIX + "output");  const tolstream = function(L) {      return lauxlib.luaL_checkudata(L, 1, lauxlib.LUA_FILEHANDLE); @@ -36,14 +37,14 @@ const f_tostring = function(L) {      if (isclosed(p))          lua.lua_pushliteral(L, "file (closed)");      else -        lua.lua_pushstring(L, lua.to_luastring(`file (${p.f.toString()})`)); +        lua.lua_pushstring(L, to_luastring(`file (${p.f.toString()})`));      return 1;  };  const tofile = function(L) {      let p = tolstream(L);      if (isclosed(p)) -        lauxlib.luaL_error(L, lua.to_luastring("attempt to use a closed file")); +        lauxlib.luaL_error(L, to_luastring("attempt to use a closed file"));      assert(p.f);      return p.f;  }; @@ -74,7 +75,7 @@ const getiofile = function(L, findex) {      lua.lua_getfield(L, lua.LUA_REGISTRYINDEX, findex);      let p = lua.lua_touserdata(L, -1);      if (isclosed(p)) -        lauxlib.luaL_error(L, lua.to_luastring("standard %s file is closed"), findex.subarray(IOPREF_LEN)); +        lauxlib.luaL_error(L, to_luastring("standard %s file is closed"), findex.subarray(IOPREF_LEN));      return p.f;  }; @@ -82,7 +83,7 @@ const g_iofile = function(L, f, mode) {      if (!lua.lua_isnoneornil(L, 1)) {          let filename = lua.lua_tostring(L, 1);          if (filename) -            lauxlib.luaL_error(L, lua.to_luastring("opening files not yet implemented")); +            lauxlib.luaL_error(L, to_luastring("opening files not yet implemented"));          else {              tofile(L);  /* check that it's a valid file handle */              lua.lua_pushvalue(L, 1); @@ -160,7 +161,7 @@ const flib = {  const createmeta = function(L) {      lauxlib.luaL_newmetatable(L, lauxlib.LUA_FILEHANDLE);  /* create metatable for file handles */      lua.lua_pushvalue(L, -1);  /* push metatable */ -    lua.lua_setfield(L, -2, lua.to_luastring("__index", true));  /* metatable.__index = metatable */ +    lua.lua_setfield(L, -2, to_luastring("__index", true));  /* metatable.__index = metatable */      lauxlib.luaL_setfuncs(L, flib, 0);  /* add file methods to new metatable */      lua.lua_pop(L, 1);  /* pop new metatable */  }; @@ -188,9 +189,9 @@ const luaopen_io = function(L) {      lauxlib.luaL_newlib(L, iolib);      createmeta(L);      /* create (and set) default files */ -    createstdfile(L, process.stdin, IO_INPUT, lua.to_luastring("stdin")); -    createstdfile(L, process.stdout, IO_OUTPUT, lua.to_luastring("stdout")); -    createstdfile(L, process.stderr, null, lua.to_luastring("stderr")); +    createstdfile(L, process.stdin, IO_INPUT, to_luastring("stdin")); +    createstdfile(L, process.stdout, IO_OUTPUT, to_luastring("stdout")); +    createstdfile(L, process.stderr, null, to_luastring("stderr"));      return 1;  }; diff --git a/src/lmathlib.js b/src/lmathlib.js index e056fd8..328356b 100644 --- a/src/lmathlib.js +++ b/src/lmathlib.js @@ -3,6 +3,7 @@  const lua     = require('./lua.js');  const lauxlib = require('./lauxlib.js');  const luaconf = require('./luaconf.js'); +const {to_luastring} = require("./fengaricore.js");  const math_random = function(L) {      let low, up; @@ -21,13 +22,13 @@ const math_random = function(L) {              up = lauxlib.luaL_checkinteger(L, 2);              break;          } -        default: return lauxlib.luaL_error(L, lua.to_luastring("wrong number of arguments", true)); +        default: return lauxlib.luaL_error(L, to_luastring("wrong number of arguments", true));      }      /* random integer in the interval [low, up] */ -    lauxlib.luaL_argcheck(L, low <= up, 1, lua.to_luastring("interval is empty", true)); +    lauxlib.luaL_argcheck(L, low <= up, 1, to_luastring("interval is empty", true));      lauxlib.luaL_argcheck(L, low >= 0 || up <= luaconf.LUA_MAXINTEGER + low, 1, -        lua.to_luastring("interval too large", true)); +        to_luastring("interval too large", true));      r *= (up - low) + 1;      lua.lua_pushinteger(L, Math.floor(r) + low); @@ -162,7 +163,7 @@ const math_rad = function(L) {  const math_min = function(L) {      let n = lua.lua_gettop(L);  /* number of arguments */      let imin = 1;  /* index of current minimum value */ -    lauxlib.luaL_argcheck(L, n >= 1, 1, lua.to_luastring("value expected", true)); +    lauxlib.luaL_argcheck(L, n >= 1, 1, to_luastring("value expected", true));      for (let i = 2; i <= n; i++){          if (lua.lua_compare(L, i, imin, lua.LUA_OPLT))              imin = i; @@ -174,7 +175,7 @@ const math_min = function(L) {  const math_max = function(L) {      let n = lua.lua_gettop(L);  /* number of arguments */      let imax = 1;  /* index of current minimum value */ -    lauxlib.luaL_argcheck(L, n >= 1, 1, lua.to_luastring("value expected", true)); +    lauxlib.luaL_argcheck(L, n >= 1, 1, to_luastring("value expected", true));      for (let i = 2; i <= n; i++){          if (lua.lua_compare(L, imax, i, lua.LUA_OPLT))              imax = i; @@ -201,7 +202,7 @@ const math_fmod = function(L) {          let d = lua.lua_tointeger(L, 2);          /* no special case needed for -1 in javascript */          if (d === 0) { -            lauxlib.luaL_argerror(L, 2, lua.to_luastring("zero", true)); +            lauxlib.luaL_argerror(L, 2, to_luastring("zero", true));          } else              lua.lua_pushinteger(L, (lua.lua_tointeger(L, 1) % d)|0);      } else { @@ -253,13 +254,13 @@ const mathlib = {  const luaopen_math = function(L) {      lauxlib.luaL_newlib(L, mathlib);      lua.lua_pushnumber(L, Math.PI); -    lua.lua_setfield(L, -2, lua.to_luastring("pi", true)); +    lua.lua_setfield(L, -2, to_luastring("pi", true));      lua.lua_pushnumber(L, Infinity); -    lua.lua_setfield(L, -2, lua.to_luastring("huge", true)); +    lua.lua_setfield(L, -2, to_luastring("huge", true));      lua.lua_pushinteger(L, luaconf.LUA_MAXINTEGER); -    lua.lua_setfield(L, -2, lua.to_luastring("maxinteger", true)); +    lua.lua_setfield(L, -2, to_luastring("maxinteger", true));      lua.lua_pushinteger(L, luaconf.LUA_MININTEGER); -    lua.lua_setfield(L, -2, lua.to_luastring("mininteger", true)); +    lua.lua_setfield(L, -2, to_luastring("mininteger", true));      return 1;  }; diff --git a/src/loadlib.js b/src/loadlib.js index 2e68ffd..2dc6d73 100644 --- a/src/loadlib.js +++ b/src/loadlib.js @@ -3,6 +3,7 @@  const fengari  = require('./fengari.js');  const lua      = require('./lua.js');  const lauxlib  = require('./lauxlib.js'); +const {luastring_indexOf, to_jsstring, to_luastring, to_uristring} = require("./fengaricore.js");  const global_env = (function() {      /* global WorkerGlobalScope */ /* see https://github.com/sindresorhus/globals/issues/127 */ @@ -21,7 +22,7 @@ const global_env = (function() {      }  })(); -const CLIBS         = lua.to_luastring("__CLIBS__", true); +const CLIBS         = to_luastring("__CLIBS__", true);  const LUA_PATH_VAR  = "LUA_PATH";  const LUA_CPATH_VAR = "LUA_CPATH"; @@ -37,13 +38,13 @@ const LUA_CSUBSEP   = lua.LUA_DIRSEP;  const LUA_LSUBSEP   = lua.LUA_DIRSEP;  /* prefix for open functions in C libraries */ -const LUA_POF       = lua.to_luastring("luaopen_"); +const LUA_POF       = to_luastring("luaopen_");  /* separator for open functions in C libraries */ -const LUA_OFSEP     = lua.to_luastring("_"); +const LUA_OFSEP     = to_luastring("_");  const LIB_FAIL      = "open"; -const AUXMARK       = lua.to_luastring("\x01"); +const AUXMARK       = to_luastring("\x01");  /* @@ -55,13 +56,13 @@ const AUXMARK       = lua.to_luastring("\x01");  let lsys_load;  if (typeof process === "undefined") {      lsys_load = function(L, path, seeglb) { -        path = lua.to_uristring(path); +        path = to_uristring(path);          let xhr = new XMLHttpRequest();          xhr.open("GET", path, false);          xhr.send();          if (xhr.status < 200 || xhr.status >= 300) { -            lua.lua_pushstring(L, lua.to_luastring(`${xhr.status}: ${xhr.statusText}`)); +            lua.lua_pushstring(L, to_luastring(`${xhr.status}: ${xhr.statusText}`));              return null;          } @@ -73,7 +74,7 @@ if (typeof process === "undefined") {          try {              func = Function("fengari", code);          } catch (e) { -            lua.lua_pushstring(L, lua.to_luastring(`${e.name}: ${e.message}`)); +            lua.lua_pushstring(L, to_luastring(`${e.name}: ${e.message}`));              return null;          }          let res = func(fengari); @@ -82,20 +83,20 @@ if (typeof process === "undefined") {          } else if (res === void 0) { /* assume library added symbols to global environment */              return global_env;          } else { -            lua.lua_pushstring(L, lua.to_luastring(`library returned unexpected type (${typeof res})`)); +            lua.lua_pushstring(L, to_luastring(`library returned unexpected type (${typeof res})`));              return null;          }      };  } else {      const pathlib = require('path');      lsys_load = function(L, path, seeglb) { -        path = lua.to_jsstring(path); +        path = to_jsstring(path);          /* relative paths should be relative to cwd, not this js file */          path = pathlib.resolve(process.cwd(), path);          try {              return require(path);          } catch (e) { -            lua.lua_pushstring(L, lua.to_luastring(e.message)); +            lua.lua_pushstring(L, to_luastring(e.message));              return null;          }      }; @@ -107,12 +108,12 @@ if (typeof process === "undefined") {  ** error string in the stack.  */  const lsys_sym = function(L, lib, sym) { -    let f = lib[lua.to_jsstring(sym)]; +    let f = lib[to_jsstring(sym)];      if (f && typeof f === 'function')          return f;      else { -        lua.lua_pushfstring(L, lua.to_luastring("undefined symbol: %s"), sym); +        lua.lua_pushfstring(L, to_luastring("undefined symbol: %s"), sym);          return null;      }  }; @@ -121,7 +122,7 @@ const lsys_sym = function(L, lib, sym) {  ** return registry.LUA_NOENV as a boolean  */  const noenv = function(L) { -    lua.lua_getfield(L, lua.LUA_REGISTRYINDEX, lua.to_luastring("LUA_NOENV")); +    lua.lua_getfield(L, lua.LUA_REGISTRYINDEX, to_luastring("LUA_NOENV"));      let b = lua.lua_toboolean(L, -1);      lua.lua_pop(L, 1);  /* remove value */      return b; @@ -143,7 +144,7 @@ if (typeof process !== "undefined") { // Only with Node  } else {      /* TODO: use async/await ? */      readable = function(path) { -        path = lua.to_uristring(path); +        path = to_uristring(path);          let xhr = new XMLHttpRequest();          /* Following GET request done by searcher_Web will be cached */          xhr.open("GET", path, false); @@ -217,21 +218,21 @@ const env = (function() {  */  const setpath = function(L, fieldname, envname, dft) {      let nver = `${envname}${lua.LUA_VERSUFFIX}`; -    lua.lua_pushstring(L, lua.to_luastring(nver)); +    lua.lua_pushstring(L, to_luastring(nver));      let path = env[nver];  /* use versioned name */      if (path === undefined)  /* no environment variable? */          path = env[envname];  /* try unversioned name */      if (path === undefined || noenv(L))  /* no environment variable? */ -        lua.lua_pushstring(L, lua.to_luastring(dft));  /* use default */ +        lua.lua_pushstring(L, to_luastring(dft));  /* use default */      else {          /* replace ";;" by ";AUXMARK;" and then AUXMARK by default path */          path = lauxlib.luaL_gsub(              L, -            lua.to_luastring(path), -            lua.to_luastring(lua.LUA_PATH_SEP + lua.LUA_PATH_SEP, true), -            lua.to_luastring(lua.LUA_PATH_SEP + lua.to_jsstring(AUXMARK) + lua.LUA_PATH_SEP, true) +            to_luastring(path), +            to_luastring(lua.LUA_PATH_SEP + lua.LUA_PATH_SEP, true), +            to_luastring(lua.LUA_PATH_SEP + to_jsstring(AUXMARK) + lua.LUA_PATH_SEP, true)          ); -        lauxlib.luaL_gsub(L, path, AUXMARK, lua.to_luastring(dft)); +        lauxlib.luaL_gsub(L, path, AUXMARK, to_luastring(dft));          lua.lua_remove(L, -2); /* remove result from 1st 'gsub' */      }      lua.lua_setfield(L, -3, fieldname);  /* package[fieldname] = path value */ @@ -265,7 +266,7 @@ const addtoclib = function(L, path, plib) {  const pushnexttemplate = function(L, path) {      while (path[0] === lua.LUA_PATH_SEP.charCodeAt(0)) path = path.subarray(1);  /* skip separators */      if (path.length === 0) return null;  /* no more templates */ -    let l = lua.luastring_indexOf(path, lua.LUA_PATH_SEP.charCodeAt(0));  /* find next separator */ +    let l = luastring_indexOf(path, lua.LUA_PATH_SEP.charCodeAt(0));  /* find next separator */      if (l < 0) l = path.length;      lua.lua_pushlstring(L, path, l);  /* template */      return path.subarray(l); @@ -277,11 +278,11 @@ const searchpath = function(L, name, path, sep, dirsep) {      if (sep[0] !== 0)  /* non-empty separator? */          name = lauxlib.luaL_gsub(L, name, sep, dirsep);  /* replace it by 'dirsep' */      while ((path = pushnexttemplate(L, path)) !== null) { -        let filename = lauxlib.luaL_gsub(L, lua.lua_tostring(L, -1), lua.to_luastring(lua.LUA_PATH_MARK, true), name); +        let filename = lauxlib.luaL_gsub(L, lua.lua_tostring(L, -1), to_luastring(lua.LUA_PATH_MARK, true), name);          lua.lua_remove(L, -2);  /* remove path template */          if (readable(filename))  /* does file exist and is readable? */              return filename;  /* return that file name */ -        lua.lua_pushfstring(L, lua.to_luastring("\n\tno file '%s'"), filename); +        lua.lua_pushfstring(L, to_luastring("\n\tno file '%s'"), filename);          lua.lua_remove(L, -2);  /* remove file name */          lauxlib.luaL_addvalue(msg);      } @@ -294,8 +295,8 @@ const ll_searchpath = function(L) {          L,          lauxlib.luaL_checkstring(L, 1),          lauxlib.luaL_checkstring(L, 2), -        lauxlib.luaL_optstring(L, 3, lua.to_luastring(".")), -        lauxlib.luaL_optstring(L, 4, lua.to_luastring(lua.LUA_DIRSEP)) +        lauxlib.luaL_optstring(L, 3, to_luastring(".")), +        lauxlib.luaL_optstring(L, 4, to_luastring(lua.LUA_DIRSEP))      );      if (f !== null) return 1;      else {  /* error message is on top of the stack */ @@ -309,8 +310,8 @@ const findfile = function(L, name, pname, dirsep) {      lua.lua_getfield(L, lua.lua_upvalueindex(1), pname);      let path = lua.lua_tostring(L, -1);      if (path === null) -        lauxlib.luaL_error(L, lua.to_luastring("'package.%s' must be a string"), pname); -    return searchpath(L, name, path, lua.to_luastring("."), dirsep); +        lauxlib.luaL_error(L, to_luastring("'package.%s' must be a string"), pname); +    return searchpath(L, name, path, to_luastring("."), dirsep);  };  const checkload = function(L, stat, filename) { @@ -318,13 +319,13 @@ const checkload = function(L, stat, filename) {          lua.lua_pushstring(L, filename);  /* will be 2nd argument to module */          return 2;  /* return open function and file name */      } else -        return lauxlib.luaL_error(L, lua.to_luastring("error loading module '%s' from file '%s':\n\t%s"), +        return lauxlib.luaL_error(L, to_luastring("error loading module '%s' from file '%s':\n\t%s"),              lua.lua_tostring(L, 1), filename, lua.lua_tostring(L, -1));  };  const searcher_Lua = function(L) {      let name = lauxlib.luaL_checkstring(L, 1); -    let filename = findfile(L, name, lua.to_luastring("path", true), lua.to_luastring(LUA_LSUBSEP, true)); +    let filename = findfile(L, name, to_luastring("path", true), to_luastring(LUA_LSUBSEP, true));      if (filename === null) return 1;  /* module not found in this path */      return checkload(L, lauxlib.luaL_loadfile(L, filename) === lua.LUA_OK, filename);  }; @@ -339,39 +340,39 @@ const searcher_Lua = function(L) {  */  const loadfunc = function(L, filename, modname) {      let openfunc; -    modname = lauxlib.luaL_gsub(L, modname, lua.to_luastring("."), LUA_OFSEP); -    let mark = lua.luastring_indexOf(modname, LUA_IGMARK.charCodeAt(0)); +    modname = lauxlib.luaL_gsub(L, modname, to_luastring("."), LUA_OFSEP); +    let mark = luastring_indexOf(modname, LUA_IGMARK.charCodeAt(0));      if (mark >= 0) {          openfunc = lua.lua_pushlstring(L, modname, mark); -        openfunc = lua.lua_pushfstring(L, lua.to_luastring("%s%s"), LUA_POF, openfunc); +        openfunc = lua.lua_pushfstring(L, to_luastring("%s%s"), LUA_POF, openfunc);          let stat = lookforfunc(L, filename, openfunc);          if (stat !== ERRFUNC) return stat;          modname = mark + 1;  /* else go ahead and try old-style name */      } -    openfunc = lua.lua_pushfstring(L, lua.to_luastring("%s%s"), LUA_POF, modname); +    openfunc = lua.lua_pushfstring(L, to_luastring("%s%s"), LUA_POF, modname);      return lookforfunc(L, filename, openfunc);  };  const searcher_C = function(L) {      let name = lauxlib.luaL_checkstring(L, 1); -    let filename = findfile(L, name, lua.to_luastring("cpath", true), lua.to_luastring(LUA_CSUBSEP, true)); +    let filename = findfile(L, name, to_luastring("cpath", true), to_luastring(LUA_CSUBSEP, true));      if (filename === null) return 1;  /* module not found in this path */      return checkload(L, (loadfunc(L, filename, name) === 0), filename);  };  const searcher_Croot = function(L) {      let name = lauxlib.luaL_checkstring(L, 1); -    let p = lua.luastring_indexOf(name, '.'.charCodeAt(0)); +    let p = luastring_indexOf(name, '.'.charCodeAt(0));      let stat;      if (p < 0) return 0;  /* is root */      lua.lua_pushlstring(L, name, p); -    let filename = findfile(L, lua.lua_tostring(L, -1), lua.to_luastring("cpath", true), lua.to_luastring(LUA_CSUBSEP, true)); +    let filename = findfile(L, lua.lua_tostring(L, -1), to_luastring("cpath", true), to_luastring(LUA_CSUBSEP, true));      if (filename === null) return 1;  /* root not found */      if ((stat = loadfunc(L, filename, name)) !== 0) {          if (stat != ERRFUNC)              return checkload(L, 0, filename);  /* real error */          else {  /* open function not found */ -            lua.lua_pushstring(L, lua.to_luastring("\n\tno module '%s' in file '%s'"), name, filename); +            lua.lua_pushstring(L, to_luastring("\n\tno module '%s' in file '%s'"), name, filename);              return 1;          }      } @@ -383,7 +384,7 @@ const searcher_preload = function(L) {      let name = lauxlib.luaL_checkstring(L, 1);      lua.lua_getfield(L, lua.LUA_REGISTRYINDEX, lauxlib.LUA_PRELOAD_TABLE);      if (lua.lua_getfield(L, -1, name) === lua.LUA_TNIL)  /* not found? */ -        lua.lua_pushfstring(L, lua.to_luastring("\n\tno field package.preload['%s']"), name); +        lua.lua_pushfstring(L, to_luastring("\n\tno field package.preload['%s']"), name);      return 1;  }; @@ -391,8 +392,8 @@ const findloader = function(L, name, ctx, k) {      let msg = new lauxlib.luaL_Buffer();  /* to build error message */      lauxlib.luaL_buffinit(L, msg);      /* push 'package.searchers' to index 3 in the stack */ -    if (lua.lua_getfield(L, lua.lua_upvalueindex(1), lua.to_luastring("searchers", true)) !== lua.LUA_TTABLE) -        lauxlib.luaL_error(L, lua.to_luastring("'package.searchers' must be a table")); +    if (lua.lua_getfield(L, lua.lua_upvalueindex(1), to_luastring("searchers", true)) !== lua.LUA_TTABLE) +        lauxlib.luaL_error(L, to_luastring("'package.searchers' must be a table"));      let ctx2 = {name: name, i: 1, msg: msg, ctx: ctx, k: k};      return findloader_cont(L, lua.LUA_OK, ctx2);  }; @@ -404,7 +405,7 @@ const findloader_cont = function(L, status, ctx) {              if (lua.lua_rawgeti(L, 3, ctx.i) === lua.LUA_TNIL) {  /* no more searchers? */                  lua.lua_pop(L, 1);  /* remove nil */                  lauxlib.luaL_pushresult(ctx.msg);  /* create error message */ -                lauxlib.luaL_error(L, lua.to_luastring("module '%s' not found:%s"), ctx.name, lua.lua_tostring(L, -1)); +                lauxlib.luaL_error(L, to_luastring("module '%s' not found:%s"), ctx.name, lua.lua_tostring(L, -1));              }              lua.lua_pushstring(L, ctx.name);              lua.lua_callk(L, 1, 2, ctx, findloader_cont);  /* call it */ @@ -475,7 +476,7 @@ const createsearcherstable = function(L) {          lua.lua_pushcclosure(L, searchers[i], 1);          lua.lua_rawseti(L, -2, i+1);      } -    lua.lua_setfield(L, -2, lua.to_luastring("searchers", true));  /* put it in field 'searchers' */ +    lua.lua_setfield(L, -2, to_luastring("searchers", true));  /* put it in field 'searchers' */  };  /* @@ -494,18 +495,18 @@ const luaopen_package = function(L) {      lauxlib.luaL_newlib(L, pk_funcs);  /* create 'package' table */      createsearcherstable(L);      /* set paths */ -    setpath(L, lua.to_luastring("path", true), LUA_PATH_VAR, lua.LUA_PATH_DEFAULT); -    setpath(L, lua.to_luastring("cpath", true), LUA_CPATH_VAR, lua.LUA_CPATH_DEFAULT); +    setpath(L, to_luastring("path", true), LUA_PATH_VAR, lua.LUA_PATH_DEFAULT); +    setpath(L, to_luastring("cpath", true), LUA_CPATH_VAR, lua.LUA_CPATH_DEFAULT);      /* store config information */      lua.lua_pushliteral(L, lua.LUA_DIRSEP + "\n" + lua.LUA_PATH_SEP + "\n" + lua.LUA_PATH_MARK + "\n" +                          lua.LUA_EXEC_DIR + "\n" + LUA_IGMARK + "\n"); -    lua.lua_setfield(L, -2, lua.to_luastring("config", true)); +    lua.lua_setfield(L, -2, to_luastring("config", true));      /* set field 'loaded' */      lauxlib.luaL_getsubtable(L, lua.LUA_REGISTRYINDEX, lauxlib.LUA_LOADED_TABLE); -    lua.lua_setfield(L, -2, lua.to_luastring("loaded", true)); +    lua.lua_setfield(L, -2, to_luastring("loaded", true));      /* set field 'preload' */      lauxlib.luaL_getsubtable(L, lua.LUA_REGISTRYINDEX, lauxlib.LUA_PRELOAD_TABLE); -    lua.lua_setfield(L, -2, lua.to_luastring("preload", true)); +    lua.lua_setfield(L, -2, to_luastring("preload", true));      lua.lua_pushglobaltable(L);      lua.lua_pushvalue(L, -2);  /* set 'package' as upvalue for next lib */      lauxlib.luaL_setfuncs(L, ll_funcs, 1);  /* open lib into global table */ diff --git a/src/loslib.js b/src/loslib.js index b5f3ddb..2266e53 100644 --- a/src/loslib.js +++ b/src/loslib.js @@ -2,25 +2,26 @@  const lua      = require('./lua.js');  const lauxlib  = require('./lauxlib.js'); +const {luastring_indexOf, to_jsstring, to_luastring} = require("./fengaricore.js");  const strftime = require('strftime');  /* options for ANSI C 89 (only 1-char options) */ -const L_STRFTIMEC89 = lua.to_luastring("aAbBcdHIjmMpSUwWxXyYZ%"); +const L_STRFTIMEC89 = to_luastring("aAbBcdHIjmMpSUwWxXyYZ%");  const LUA_STRFTIMEOPTIONS = L_STRFTIMEC89;  /* options for ISO C 99 and POSIX */ -// const L_STRFTIMEC99 = lua.to_luastring("aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%||EcECExEXEyEYOdOeOHOIOmOMOSOuOUOVOwOWOy");  /* two-char options */ +// const L_STRFTIMEC99 = to_luastring("aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%||EcECExEXEyEYOdOeOHOIOmOMOSOuOUOVOwOWOy");  /* two-char options */  // const LUA_STRFTIMEOPTIONS = L_STRFTIMEC99;  /* options for Windows */ -// const L_STRFTIMEWIN = lua.to_luastring("aAbBcdHIjmMpSUwWxXyYzZ%||#c#x#d#H#I#j#m#M#S#U#w#W#y#Y");  /* two-char options */ +// const L_STRFTIMEWIN = to_luastring("aAbBcdHIjmMpSUwWxXyYzZ%||#c#x#d#H#I#j#m#M#S#U#w#W#y#Y");  /* two-char options */  // const LUA_STRFTIMEOPTIONS = L_STRFTIMEWIN;  const setfield = function(L, key, value) {      lua.lua_pushinteger(L, value); -    lua.lua_setfield(L, -2, lua.to_luastring(key, true)); +    lua.lua_setfield(L, -2, to_luastring(key, true));  };  const setallfields = function(L, time, utc) { @@ -39,18 +40,18 @@ const setallfields = function(L, time, utc) {  const L_MAXDATEFIELD = (Number.MAX_SAFE_INTEGER / 2);  const getfield = function(L, key, d, delta) { -    let t = lua.lua_getfield(L, -1, lua.to_luastring(key, true));  /* get field and its type */ +    let t = lua.lua_getfield(L, -1, to_luastring(key, true));  /* get field and its type */      let res = lua.lua_tointegerx(L, -1);      if (res === false) {  /* field is not an integer? */          if (t !== lua.LUA_TNIL)  /* some other value? */ -            return lauxlib.luaL_error(L, lua.to_luastring("field '%s' is not an integer"), key); +            return lauxlib.luaL_error(L, to_luastring("field '%s' is not an integer"), key);          else if (d < 0)  /* absent field; no default? */ -            return lauxlib.luaL_error(L, lua.to_luastring("field '%s' missing in date table"), key); +            return lauxlib.luaL_error(L, to_luastring("field '%s' missing in date table"), key);          res = d;      }      else {          if (!(-L_MAXDATEFIELD <= res && res <= L_MAXDATEFIELD)) -            return lauxlib.luaL_error(L, lua.to_luastring("field '%s' is out-of-bound"), key); +            return lauxlib.luaL_error(L, to_luastring("field '%s' is out-of-bound"), key);          res -= delta;      }      lua.lua_pop(L, 1); @@ -78,7 +79,7 @@ const checkoption = function(L, conv, i, buff) {          }      }      lauxlib.luaL_argerror(L, 1, -        lua.lua_pushfstring(L, lua.to_luastring("invalid conversion specifier '%%%s'"), conv)); +        lua.lua_pushfstring(L, to_luastring("invalid conversion specifier '%%%s'"), conv));  };  /* maximum size for an individual 'strftime' item */ @@ -86,7 +87,7 @@ const checkoption = function(L, conv, i, buff) {  const os_date = function(L) { -    let s = lauxlib.luaL_optlstring(L, 1, lua.to_luastring("%c")); +    let s = lauxlib.luaL_optlstring(L, 1, to_luastring("%c"));      let t = lauxlib.luaL_opt(L, l_checktime, 2, new Date().getTime() / 1000) * 1000;      let stm = new Date(t);      let utc = false; @@ -97,7 +98,7 @@ const os_date = function(L) {      }      if (stm === null)  /* invalid date? */ -        lauxlib.luaL_error(L, lua.to_luastring("time result cannot be represented in this installation", true)); +        lauxlib.luaL_error(L, to_luastring("time result cannot be represented in this installation", true));      if (s[i] === "*".charCodeAt(0) && s[i+1] === "t".charCodeAt(0)) {          lua.lua_createtable(L, 0, 9);  /* 9 = number of fields */          setallfields(L, stm, utc); @@ -112,11 +113,11 @@ const os_date = function(L) {              } else {                  i++;  /* skip '%' */                  i = checkoption(L, s, i, cc.subarray(1));  /* copy specifier to 'cc' */ -                let len = lua.luastring_indexOf(cc, 0); +                let len = luastring_indexOf(cc, 0);                  if (len !== -1)                      cc = cc.subarray(0, len); -                let buff = strftime(lua.to_jsstring(cc), stm); -                lauxlib.luaL_addstring(b, lua.to_luastring(buff)); +                let buff = strftime(to_jsstring(cc), stm); +                lauxlib.luaL_addstring(b, to_luastring(buff));              }          }          lauxlib.luaL_pushresult(b); @@ -144,7 +145,7 @@ const os_time = function(L) {  const l_checktime = function(L, arg) {      let t = lauxlib.luaL_checkinteger(L, arg); -    // lauxlib.luaL_argcheck(L, t, arg, lua.to_luastring("time out-of-bounds")); +    // lauxlib.luaL_argcheck(L, t, arg, to_luastring("time out-of-bounds"));      return t;  }; @@ -186,7 +187,7 @@ if (typeof process === "undefined") {      syslib.getenv = function(L) {          let key = lauxlib.luaL_checkstring(L, 1); -        key = lua.to_jsstring(key); /* https://github.com/nodejs/node/issues/16961 */ +        key = to_jsstring(key); /* https://github.com/nodejs/node/issues/16961 */          if (Object.prototype.hasOwnProperty.call(process.env, key)) {              lua.lua_pushliteral(L, process.env[key]);          } else { @@ -233,8 +234,8 @@ if (typeof process === "undefined") {      syslib.tmpname = function(L) {          let name = lua_tmpname();          if (!name) -            return lauxlib.luaL_error(L, lua.to_luastring("unable to generate a unique filename")); -        lua.lua_pushstring(L, lua.to_luastring(name)); +            return lauxlib.luaL_error(L, to_luastring("unable to generate a unique filename")); +        lua.lua_pushstring(L, to_luastring(name));          return 1;      }; diff --git a/src/lstrlib.js b/src/lstrlib.js index 6986411..5477750 100644 --- a/src/lstrlib.js +++ b/src/lstrlib.js @@ -6,6 +6,7 @@ const sprintf = require('sprintf-js').sprintf;  const lauxlib = require('./lauxlib.js');  const lua     = require('./lua.js');  const luaconf = require('./luaconf.js'); +const {luastring_indexOf, to_jsstring, to_luastring} = require("./fengaricore.js");  const sL_ESC  = '%';  const L_ESC   = sL_ESC.charCodeAt(0); @@ -22,7 +23,7 @@ const MAXSIZE = 2147483647;  /* Give natural (i.e. strings end at the first \0) length of a string represented by an array of bytes */  const strlen = function(s) { -    let len = lua.luastring_indexOf(s, 0); +    let len = luastring_indexOf(s, 0);      return len > -1 ? len : s.length;  }; @@ -76,7 +77,7 @@ const str_dump = function(L) {      lua.lua_settop(L, 1);      lauxlib.luaL_buffinit(L, b);      if (lua.lua_dump(L, writer, b, strip) !== 0) -        return lauxlib.luaL_error(L, lua.to_luastring("unable to dump given function")); +        return lauxlib.luaL_error(L, to_luastring("unable to dump given function"));      lauxlib.luaL_pushresult(b);      return 1;  }; @@ -88,17 +89,17 @@ const L_NBFD = 1;  const num2straux = function(x) {      /* if 'inf' or 'NaN', format it like '%g' */      if (Object.is(x, Infinity)) -        return lua.to_luastring('inf'); +        return to_luastring('inf');      else if (Object.is(x, -Infinity)) -        return lua.to_luastring('-inf'); +        return to_luastring('-inf');      else if (Number.isNaN(x)) -        return lua.to_luastring('nan'); +        return to_luastring('nan');      else if (x === 0) {  /* can be -0... */          /* create "0" or "-0" followed by exponent */          let zero = sprintf(luaconf.LUA_NUMBER_FMT + "x0p+0", x);          if (Object.is(x, -0))              zero = "-" + zero; -        return lua.to_luastring(zero); +        return to_luastring(zero);      } else {          let buff = "";          let fe = luaconf.frexp(x);  /* 'x' fraction and exponent */ @@ -112,7 +113,7 @@ const num2straux = function(x) {          buff += (m * (1<<L_NBFD)).toString(16);          e -= L_NBFD;  /* this digit goes before the radix point */          buff += sprintf("p%+d", e);  /* add exponent */ -        return lua.to_luastring(buff); +        return to_luastring(buff);      }  }; @@ -122,7 +123,7 @@ const lua_number2strx = function(L, fmt, x) {          for (let i = 0; i < buff.length; i++)              buff[i] = String.fromCharCode(buff[i]).toUpperCase().charCodeAt(0);      } else if (fmt[SIZELENMOD] !== 'a'.charCodeAt(0)) -        lauxlib.luaL_error(L, lua.to_luastring("modifiers for format '%%a'/'%%A' not implemented")); +        lauxlib.luaL_error(L, to_luastring("modifiers for format '%%a'/'%%A' not implemented"));      return buff;  }; @@ -166,9 +167,9 @@ const addquoted = function(b, s, len) {          } else if (iscntrl(s[i])) {              let buff;              if (!isdigit(s[i+1])) -                buff = lua.to_luastring(sprintf("\\%d", s[i])); +                buff = to_luastring(sprintf("\\%d", s[i]));              else -                buff = lua.to_luastring(sprintf("\\%03d", s[i])); +                buff = to_luastring(sprintf("\\%03d", s[i]));              lauxlib.luaL_addstring(b, buff);          } else              lauxlib.luaL_addchar(b, s[i]); @@ -181,9 +182,9 @@ const addquoted = function(b, s, len) {  ** Ensures the 'buff' string uses a dot as the radix character.  */  const checkdp = function(buff) { -    if (lua.luastring_indexOf(buff, '.'.charCodeAt(0)) < 0) {  /* no dot? */ +    if (luastring_indexOf(buff, '.'.charCodeAt(0)) < 0) {  /* no dot? */          let point = luaconf.lua_getlocaledecpoint().charCodeAt(0);  /* try locale point */ -        let ppoint = lua.luastring_indexOf(buff, point); +        let ppoint = luastring_indexOf(buff, point);          if (ppoint) buff[ppoint] = '.';  /* change it to a dot */      }  }; @@ -199,14 +200,14 @@ const addliteral = function(L, b, arg) {              let buff;              if (!lua.lua_isinteger(L, arg)) {  /* float? */                  let n = lua.lua_tonumber(L, arg);  /* write as hexa ('%a') */ -                buff = lua_number2strx(L, lua.to_luastring(`%${luaconf.LUA_INTEGER_FRMLEN}a`), n); +                buff = lua_number2strx(L, to_luastring(`%${luaconf.LUA_INTEGER_FRMLEN}a`), n);                  checkdp(buff);  /* ensure it uses a dot */              } else {  /* integers */                  let n = lua.lua_tointeger(L, arg);                  let format = (n === luaconf.LUA_MININTEGER)  /* corner case? */                      ? "0x%" + luaconf.LUA_INTEGER_FRMLEN + "x"  /* use hexa */                      : luaconf.LUA_INTEGER_FMT;  /* else use default format */ -                buff = lua.to_luastring(sprintf(format, n)); +                buff = to_luastring(sprintf(format, n));              }              lauxlib.luaL_addstring(b, buff);              break; @@ -217,16 +218,16 @@ const addliteral = function(L, b, arg) {              break;          }          default: { -            lauxlib.luaL_argerror(L, arg, lua.to_luastring("value has no literal form", true)); +            lauxlib.luaL_argerror(L, arg, to_luastring("value has no literal form", true));          }      }  };  const scanformat = function(L, strfrmt, i, form) {      let p = i; -    while (strfrmt[p] !== 0 && lua.luastring_indexOf(FLAGS, strfrmt[p]) >= 0) p++;  /* skip flags */ +    while (strfrmt[p] !== 0 && luastring_indexOf(FLAGS, strfrmt[p]) >= 0) p++;  /* skip flags */      if (p - i >= FLAGS.length) -        lauxlib.luaL_error(L, lua.to_luastring("invalid format (repeated flags)", true)); +        lauxlib.luaL_error(L, to_luastring("invalid format (repeated flags)", true));      if (isdigit(strfrmt[p])) p++;  /* skip width */      if (isdigit(strfrmt[p])) p++;  /* (2 digits at most) */      if (strfrmt[p] === '.'.charCodeAt(0)) { @@ -235,7 +236,7 @@ const scanformat = function(L, strfrmt, i, form) {          if (isdigit(strfrmt[p])) p++;  /* (2 digits at most) */      }      if (isdigit(strfrmt[p])) -        lauxlib.luaL_error(L, lua.to_luastring("invalid format (width or precision too long)", true)); +        lauxlib.luaL_error(L, to_luastring("invalid format (width or precision too long)", true));      form[0] = "%".charCodeAt(0);      for (let j = 0; j < p - i + 1; j++)          form[j+1] = strfrmt[i+j]; @@ -270,7 +271,7 @@ const str_format = function(L) {          } else { /* format item */              let form = [];  /* to store the format ('%...') */              if (++arg > top) -                lauxlib.luaL_argerror(L, arg, lua.to_luastring("no value", true)); +                lauxlib.luaL_argerror(L, arg, to_luastring("no value", true));              i = scanformat(L, strfrmt, i, form);              switch (String.fromCharCode(strfrmt[i++])) {                  case 'c': { @@ -282,7 +283,7 @@ const str_format = function(L) {                  case 'o': case 'u': case 'x': case 'X': {                      let n = lauxlib.luaL_checkinteger(L, arg);                      addlenmod(form, luaconf.LUA_INTEGER_FRMLEN.split('').map(e => e.charCodeAt(0))); -                    lauxlib.luaL_addstring(b, lua.to_luastring(sprintf(String.fromCharCode(...form), n))); +                    lauxlib.luaL_addstring(b, to_luastring(sprintf(String.fromCharCode(...form), n)));                      break;                  }                  case 'a': case 'A': { @@ -294,7 +295,7 @@ const str_format = function(L) {                  case 'g': case 'G': {                      let n = lauxlib.luaL_checknumber(L, arg);                      addlenmod(form, luaconf.LUA_INTEGER_FRMLEN.split('').map(e => e.charCodeAt(0))); -                    lauxlib.luaL_addstring(b, lua.to_luastring(sprintf(String.fromCharCode(...form), n))); +                    lauxlib.luaL_addstring(b, to_luastring(sprintf(String.fromCharCode(...form), n)));                      break;                  }                  case 'q': { @@ -306,20 +307,20 @@ const str_format = function(L) {                      if (form.length <= 2 || form[2] === 0) {  /* no modifiers? */                          lauxlib.luaL_addvalue(b);  /* keep entire string */                      } else { -                        lauxlib.luaL_argcheck(L, s.length === strlen(s), arg, lua.to_luastring("string contains zeros", true)); -                        if (lua.luastring_indexOf(form, '.'.charCodeAt(0)) < 0 && s.length >= 100) { +                        lauxlib.luaL_argcheck(L, s.length === strlen(s), arg, to_luastring("string contains zeros", true)); +                        if (luastring_indexOf(form, '.'.charCodeAt(0)) < 0 && s.length >= 100) {                              /* no precision and string is too long to be formatted */                              lauxlib.luaL_addvalue(b);  /* keep entire string */                          } else {  /* format the string into 'buff' */                              // TODO: will fail if s is not valid UTF-8 -                            lauxlib.luaL_addstring(b, lua.to_luastring(sprintf(String.fromCharCode(...form), lua.to_jsstring(s)))); +                            lauxlib.luaL_addstring(b, to_luastring(sprintf(String.fromCharCode(...form), to_jsstring(s))));                              lua.lua_pop(L, 1);  /* remove result from 'luaL_tolstring' */                          }                      }                      break;                  }                  default: {  /* also treat cases 'pnLlh' */ -                    return lauxlib.luaL_error(L, lua.to_luastring("invalid option '%%%c' to 'format'"), strfrmt[i-1]); +                    return lauxlib.luaL_error(L, to_luastring("invalid option '%%%c' to 'format'"), strfrmt[i-1]);                  }              }          } @@ -393,7 +394,7 @@ const getnum = function(fmt, df) {  const getnumlimit = function(h, fmt, df) {      let sz = getnum(fmt, df);      if (sz > MAXINTSIZE || sz <= 0) -        lauxlib.luaL_error(h.L, lua.to_luastring("integral size (%d) out of limits [1,%d]"), sz, MAXINTSIZE); +        lauxlib.luaL_error(h.L, to_luastring("integral size (%d) out of limits [1,%d]"), sz, MAXINTSIZE);      return sz;  }; @@ -427,7 +428,7 @@ const getoption = function(h, fmt) {          case 'c'.charCodeAt(0): {              r.size = getnum(fmt, -1);              if (r.size === -1) -                lauxlib.luaL_error(h.L, lua.to_luastring("missing size for format option 'c'")); +                lauxlib.luaL_error(h.L, to_luastring("missing size for format option 'c'"));              r.opt = KOption.Kchar;              return r;          } @@ -439,7 +440,7 @@ const getoption = function(h, fmt) {          case '>'.charCodeAt(0): h.islittle = false; break;          case '='.charCodeAt(0): h.islittle = true; break;          case '!'.charCodeAt(0): h.maxalign = getnumlimit(h, fmt, MAXALIGN); break; -        default: lauxlib.luaL_error(h.L, lua.to_luastring("invalid format option '%c'"), r.opt); +        default: lauxlib.luaL_error(h.L, to_luastring("invalid format option '%c'"), r.opt);      }      r.opt = KOption.Knop; @@ -468,13 +469,13 @@ const getdetails = function(h, totalsize, fmt) {      let align = r.size;  /* usually, alignment follows size */      if (r.opt === KOption.Kpaddalign) {  /* 'X' gets alignment from following option */          if (fmt.off >= fmt.s.length || fmt.s[fmt.off] === 0) -            lauxlib.luaL_argerror(h.L, 1, lua.to_luastring("invalid next option for option 'X'", true)); +            lauxlib.luaL_argerror(h.L, 1, to_luastring("invalid next option for option 'X'", true));          else {              let o = getoption(h, fmt);              align = o.size;              o = o.opt;              if (o === KOption.Kchar || align === 0) -                lauxlib.luaL_argerror(h.L, 1, lua.to_luastring("invalid next option for option 'X'", true)); +                lauxlib.luaL_argerror(h.L, 1, to_luastring("invalid next option for option 'X'", true));          }      }      if (align <= 1 || r.opt === KOption.Kchar)  /* need no alignment? */ @@ -483,7 +484,7 @@ const getdetails = function(h, totalsize, fmt) {          if (align > h.maxalign)  /* enforce maximum alignment */              align = h.maxalign;          if ((align & (align -1)) !== 0)  /* is 'align' not a power of 2? */ -            lauxlib.luaL_argerror(h.L, 1, lua.to_luastring("format asks for alignment not power of 2", true)); +            lauxlib.luaL_argerror(h.L, 1, to_luastring("format asks for alignment not power of 2", true));          r.ntoalign = (align - (totalsize & (align - 1))) & (align - 1);      }      return r; @@ -534,7 +535,7 @@ const str_pack = function(L) {                  let n = lauxlib.luaL_checkinteger(L, arg);                  if (size < SZINT) {  /* need overflow check? */                      let lim = 1 << (size * 8) - 1; -                    lauxlib.luaL_argcheck(L, -lim <= n && n < lim, arg, lua.to_luastring("integer overflow", true)); +                    lauxlib.luaL_argcheck(L, -lim <= n && n < lim, arg, to_luastring("integer overflow", true));                  }                  packint(b, n, h.islittle, size, n < 0);                  break; @@ -542,7 +543,7 @@ const str_pack = function(L) {              case KOption.Kuint: {  /* unsigned integers */                  let n = lauxlib.luaL_checkinteger(L, arg);                  if (size < SZINT) -                    lauxlib.luaL_argcheck(L, (n>>>0) < (1 << (size * NB)), arg, lua.to_luastring("unsigned overflow", true)); +                    lauxlib.luaL_argcheck(L, (n>>>0) < (1 << (size * NB)), arg, to_luastring("unsigned overflow", true));                  packint(b, n>>>0, h.islittle, size, false);                  break;              } @@ -558,7 +559,7 @@ const str_pack = function(L) {              case KOption.Kchar: {  /* fixed-size string */                  let s = lauxlib.luaL_checkstring(L, arg);                  let len = s.length; -                lauxlib.luaL_argcheck(L, len <= size, arg, lua.to_luastring("string longer than given size", true)); +                lauxlib.luaL_argcheck(L, len <= size, arg, to_luastring("string longer than given size", true));                  lauxlib.luaL_addlstring(b, s, len);  /* add string */                  while (len++ < size)  /* pad extra space */                      lauxlib.luaL_addchar(b, LUAL_PACKPADBYTE); @@ -569,7 +570,7 @@ const str_pack = function(L) {                  let len = s.length;                  lauxlib.luaL_argcheck(L,                      size >= 4 /* sizeof(size_t) */ || len < (1 << (size * NB)), -                    arg, lua.to_luastring("string length does not fit in given size", true)); +                    arg, to_luastring("string length does not fit in given size", true));                  packint(b, len, h.islittle, size, 0);  /* pack length */                  lauxlib.luaL_addlstring(b, s, len);                  totalsize += len; @@ -578,7 +579,7 @@ const str_pack = function(L) {              case KOption.Kzstr: {  /* zero-terminated string */                  let s = lauxlib.luaL_checkstring(L, arg);                  let len = s.length; -                lauxlib.luaL_argcheck(L, lua.luastring_indexOf(s, 0) < 0, arg, lua.to_luastring("strings contains zeros", true)); +                lauxlib.luaL_argcheck(L, luastring_indexOf(s, 0) < 0, arg, to_luastring("strings contains zeros", true));                  lauxlib.luaL_addlstring(b, s, len);                  lauxlib.luaL_addchar(b, 0);  /* add zero at the end */                  totalsize += len + 1; @@ -607,14 +608,14 @@ const str_reverse = function(L) {  const str_lower = function(L) {      let s = lauxlib.luaL_checkstring(L, 1);      // TODO: will fail on invalid UTF-8 -    lua.lua_pushstring(L, lua.to_luastring(lua.to_jsstring(s).toLowerCase())); +    lua.lua_pushstring(L, to_luastring(to_jsstring(s).toLowerCase()));      return 1;  };  const str_upper = function(L) {      let s = lauxlib.luaL_checkstring(L, 1);      // TODO: will fail on invalid UTF-8 -    lua.lua_pushstring(L, lua.to_luastring(lua.to_jsstring(s).toUpperCase())); +    lua.lua_pushstring(L, to_luastring(to_jsstring(s).toUpperCase()));      return 1;  }; @@ -622,11 +623,11 @@ const str_rep = function(L) {      let s = lauxlib.luaL_checkstring(L, 1);      let l = s.length;      let n = lauxlib.luaL_checkinteger(L, 2); -    let sep = lauxlib.luaL_optstring(L, 3, lua.to_luastring("")); +    let sep = lauxlib.luaL_optstring(L, 3, to_luastring(""));      let lsep = sep.length;      if (n <= 0) lua.lua_pushliteral(L, "");      else if (l + lsep < l || l + lsep > MAXSIZE / n)  /* may overflow? */ -        return lauxlib.luaL_error(L, lua.to_luastring("resulting string too large")); +        return lauxlib.luaL_error(L, to_luastring("resulting string too large"));      else {          let totallen = n * l + (n - 1) * lsep;          let b = new lauxlib.luaL_Buffer(); @@ -656,10 +657,10 @@ const str_byte = function(L) {      if (pose > l) pose = l;      if (posi > pose) return 0;  /* empty interval; return no values */      if (pose - posi >= Number.MAX_SAFE_INTEGER)  /* arithmetic overflow? */ -        return lauxlib.luaL_error(L, lua.to_luastring("string slice too long", true)); +        return lauxlib.luaL_error(L, to_luastring("string slice too long", true));      let n = (pose - posi) + 1; -    lauxlib.luaL_checkstack(L, n, lua.to_luastring("string slice too long", true)); +    lauxlib.luaL_checkstack(L, n, to_luastring("string slice too long", true));      for (let i = 0; i < n; i++)          lua.lua_pushinteger(L, s[posi + i - 1]);      return n; @@ -678,12 +679,12 @@ const str_packsize = function(L) {          let size = details.size;          let ntoalign = details.ntoalign;          size += ntoalign;  /* total space used by option */ -        lauxlib.luaL_argcheck(L, totalsize <= MAXSIZE - size, 1, lua.to_luastring("format result too large", true)); +        lauxlib.luaL_argcheck(L, totalsize <= MAXSIZE - size, 1, to_luastring("format result too large", true));          totalsize += size;          switch (opt) {              case KOption.Kstring:  /* strings with length count */              case KOption.Kzstr:    /* zero-terminated string */ -                lauxlib.luaL_argerror(L, 1, lua.to_luastring("variable-length format", true)); +                lauxlib.luaL_argerror(L, 1, to_luastring("variable-length format", true));                  /* call never return, but to avoid warnings: *//* fall through */              default:  break;          } @@ -716,7 +717,7 @@ const unpackint = function(L, str, islittle, size, issigned) {          let mask = !issigned || res >= 0 ? 0 : MC;          for (let i = limit; i < size; i++) {              if (str[islittle ? i : size - 1 - i] !== mask) -                lauxlib.luaL_error(L, lua.to_luastring("%d-byte integer does not fit into Lua Integer"), size); +                lauxlib.luaL_error(L, to_luastring("%d-byte integer does not fit into Lua Integer"), size);          }      }      return res; @@ -743,17 +744,17 @@ const str_unpack = function(L) {      let ld = data.length;      let pos = posrelat(lauxlib.luaL_optinteger(L, 3, 1), ld) - 1;      let n = 0;  /* number of results */ -    lauxlib.luaL_argcheck(L, pos <= ld && pos >= 0, 3, lua.to_luastring("initial position out of string", true)); +    lauxlib.luaL_argcheck(L, pos <= ld && pos >= 0, 3, to_luastring("initial position out of string", true));      while (fmt.off < fmt.s.length) {          let details = getdetails(h, pos, fmt);          let opt = details.opt;          let size = details.size;          let ntoalign = details.ntoalign;          if (/*ntoalign + size > ~pos ||*/ pos + ntoalign + size > ld) -            lauxlib.luaL_argerror(L, 2, lua.to_luastring("data string too short", true)); +            lauxlib.luaL_argerror(L, 2, to_luastring("data string too short", true));          pos += ntoalign;  /* skip alignment */          /* stack space for item + next position */ -        lauxlib.luaL_checkstack(L, 2, lua.to_luastring("too many results", true)); +        lauxlib.luaL_checkstack(L, 2, to_luastring("too many results", true));          n++;          switch (opt) {              case KOption.Kint: @@ -773,13 +774,13 @@ const str_unpack = function(L) {              }              case KOption.Kstring: {                  let len = unpackint(L, data.subarray(pos), h.islittle, size, 0); -                lauxlib.luaL_argcheck(L, pos + len + size <= ld, 2, lua.to_luastring("data string too short", true)); +                lauxlib.luaL_argcheck(L, pos + len + size <= ld, 2, to_luastring("data string too short", true));                  lua.lua_pushstring(L, data.subarray(pos + size, pos + size + len));                  pos += len;  /* skip string */                  break;              }              case KOption.Kzstr: { -                let e = lua.luastring_indexOf(data, 0, pos); +                let e = luastring_indexOf(data, 0, pos);                  if (e === -1) e = data.length - pos;                  lua.lua_pushstring(L, data.subarray(pos, e));                  pos = e + 1;  /* skip string plus final '\0' */ @@ -817,7 +818,7 @@ class MatchState {  const check_capture = function(ms, l) {      l = l - '1'.charCodeAt(0);      if (l < 0 || l >= ms.level || ms.capture[l].len === CAP_UNFINISHED) -        return lauxlib.luaL_error(ms.L, lua.to_luastring("invalid capture index %%%d"), l + 1); +        return lauxlib.luaL_error(ms.L, to_luastring("invalid capture index %%%d"), l + 1);      return l;  }; @@ -825,21 +826,21 @@ const capture_to_close = function(ms) {      let level = ms.level;      for (level--; level >= 0; level--)          if (ms.capture[level].len === CAP_UNFINISHED) return level; -    return lauxlib.luaL_error(ms.L, lua.to_luastring("invalid pattern capture")); +    return lauxlib.luaL_error(ms.L, to_luastring("invalid pattern capture"));  };  const classend = function(ms, p) {      switch(ms.p[p++]) {          case L_ESC: {              if (p === ms.p_end) -                lauxlib.luaL_error(ms.L, lua.to_luastring("malformed pattern (ends with '%%')")); +                lauxlib.luaL_error(ms.L, to_luastring("malformed pattern (ends with '%%')"));              return p + 1;          }          case '['.charCodeAt(0): {              if (ms.p[p] === '^'.charCodeAt(0)) p++;              do {  /* look for a ']' */                  if (p === ms.p_end) -                    lauxlib.luaL_error(ms.L, lua.to_luastring("malformed pattern (missing ']')")); +                    lauxlib.luaL_error(ms.L, to_luastring("malformed pattern (missing ']')"));                  if (ms.p[p++] === L_ESC && p < ms.p_end)                      p++;  /* skip escapes (e.g. '%]') */              } while (ms.p[p] !== ']'.charCodeAt(0)); @@ -906,7 +907,7 @@ const singlematch = function(ms, s, p, ep) {  const matchbalance = function(ms, s, p) {      if (p >= ms.p_end - 1) -        lauxlib.luaL_error(ms.L, lua.to_luastring("malformed pattern (missing arguments to '%%b'")); +        lauxlib.luaL_error(ms.L, to_luastring("malformed pattern (missing arguments to '%%b'"));      if (ms.src[s] !== ms.p[p])          return null;      else { @@ -949,7 +950,7 @@ const min_expand = function(ms, s, p, ep) {  const start_capture = function(ms, s, p, what) {      let level = ms.level; -    if (level >= LUA_MAXCAPTURES) lauxlib.luaL_error(ms.L, lua.to_luastring("too many captures", true)); +    if (level >= LUA_MAXCAPTURES) lauxlib.luaL_error(ms.L, to_luastring("too many captures", true));      ms.capture[level] = ms.capture[level] ? ms.capture[level] : {};      ms.capture[level].init = s;      ms.capture[level].len = what; @@ -975,7 +976,7 @@ const array_cmp = function(a, ai, b, bi, len) {          return true;      let aj = ai+len;      loop: for (;;) { -        ai = lua.luastring_indexOf(a, b[bi], ai); +        ai = luastring_indexOf(a, b[bi], ai);          if (ai === -1 || ai >= aj)              return false;          for (let j = 1; j < len; j++) { @@ -1001,7 +1002,7 @@ const match = function(ms, s, p) {      let gotoinit = true;      if (ms.matchdepth-- === 0) -        lauxlib.luaL_error(ms.L, lua.to_luastring("pattern too complex", true)); +        lauxlib.luaL_error(ms.L, to_luastring("pattern too complex", true));      while (gotoinit || gotodefault) {          gotoinit = false; @@ -1039,7 +1040,7 @@ const match = function(ms, s, p) {                          case 'f'.charCodeAt(0): {  /* frontier? */                              p += 2;                              if (ms.p[p] !== '['.charCodeAt(0)) -                                lauxlib.luaL_error(ms.L, lua.to_luastring("missing '[' after '%%f' in pattern")); +                                lauxlib.luaL_error(ms.L, to_luastring("missing '[' after '%%f' in pattern"));                              let ep = classend(ms, p);  /* points to what is next */                              let previous = s === ms.src_init ? 0 : ms.src[s-1];                              if (!matchbracketclass(ms, previous, p, ep - 1) && matchbracketclass(ms, (s===ms.src_end)?0:ms.src[s], p, ep - 1)) { @@ -1108,10 +1109,10 @@ const push_onecapture = function(ms, i, s, e) {          if (i === 0)              lua.lua_pushlstring(ms.L, ms.src.subarray(s, e), e - s);  /* add whole match */          else -            lauxlib.luaL_error(ms.L, lua.to_luastring("invalid capture index %%%d"), i + 1); +            lauxlib.luaL_error(ms.L, to_luastring("invalid capture index %%%d"), i + 1);      } else {          let l = ms.capture[i].len; -        if (l === CAP_UNFINISHED) lauxlib.luaL_error(ms.L, lua.to_luastring("unfinished capture", true)); +        if (l === CAP_UNFINISHED) lauxlib.luaL_error(ms.L, to_luastring("unfinished capture", true));          if (l === CAP_POSITION)              lua.lua_pushinteger(ms.L, ms.capture[i].init - ms.src_init + 1);          else @@ -1121,7 +1122,7 @@ const push_onecapture = function(ms, i, s, e) {  const push_captures = function(ms, s, e) {      let nlevels = ms.level === 0 && ms.src.subarray(s) ? 1 : ms.level; -    lauxlib.luaL_checkstack(ms.L, nlevels, lua.to_luastring("too many catpures", true)); +    lauxlib.luaL_checkstack(ms.L, nlevels, to_luastring("too many catpures", true));      for (let i = 0; i < nlevels; i++)          push_onecapture(ms, i, s, e);      return nlevels;  /* number of strings pushed */ @@ -1275,7 +1276,7 @@ const add_s = function(ms, b, s, e) {              i++;  /* skip ESC */              if (!isdigit(news[i])) {                  if (news[i] !== L_ESC) -                    lauxlib.luaL_error(L, lua.to_luastring("invalid use of '%c' in replacement string"), L_ESC); +                    lauxlib.luaL_error(L, to_luastring("invalid use of '%c' in replacement string"), L_ESC);                  lauxlib.luaL_addchar(b, news[i]);              } else if (news[i] === '0'.charCodeAt(0))                  lauxlib.luaL_addlstring(b, ms.src.subarray(s, e), e - s); @@ -1312,7 +1313,7 @@ const add_value = function(ms, b, s, e, tr) {          lua.lua_pop(L, 1);          lua.lua_pushlstring(L, ms.src.subarray(s, e), e - s);  /* keep original text */      } else if (!lua.lua_isstring(L, -1)) -        lauxlib.luaL_error(L, lua.to_luastring("invalid replacement value (a %s)"), lauxlib.luaL_typename(L, -1)); +        lauxlib.luaL_error(L, to_luastring("invalid replacement value (a %s)"), lauxlib.luaL_typename(L, -1));      lauxlib.luaL_addvalue(b);  /* add result to accumulator */  }; @@ -1329,7 +1330,7 @@ const str_gsub = function(L) {      let ms = new MatchState(L);      let b = new lauxlib.luaL_Buffer();      lauxlib.luaL_argcheck(L, tr === lua.LUA_TNUMBER || tr === lua.LUA_TSTRING || tr === lua.LUA_TFUNCTION || tr === lua.LUA_TTABLE, 3, -        lua.to_luastring("string/function/table expected", true)); +        to_luastring("string/function/table expected", true));      lauxlib.luaL_buffinit(L, b);      if (anchor) {          p = p.subarray(1); lp--;  /* skip anchor character */ @@ -1381,7 +1382,7 @@ const createmetatable = function(L) {      lua.lua_setmetatable(L, -2);  /* set table as metatable for strings */      lua.lua_pop(L, 1);  /* pop dummy string */      lua.lua_pushvalue(L, -2);  /* get string library */ -    lua.lua_setfield(L, -2, lua.to_luastring("__index", true));  /* metatable.__index = string */ +    lua.lua_setfield(L, -2, to_luastring("__index", true));  /* metatable.__index = string */      lua.lua_pop(L, 1);  /* pop metatable */  }; diff --git a/src/ltablib.js b/src/ltablib.js index 9998f3c..a24a275 100644 --- a/src/ltablib.js +++ b/src/ltablib.js @@ -5,7 +5,7 @@ const assert  = require('assert');  const lua     = require('./lua.js');  const lauxlib = require('./lauxlib.js');  const luaconf = require('./luaconf.js'); - +const {to_luastring} = require("./fengaricore.js");  /*  ** Operations that an object must define to mimic a table @@ -29,9 +29,9 @@ const checktab = function(L, arg, what) {      if (lua.lua_type(L, arg) !== lua.LUA_TTABLE) {  /* is it not a table? */          let n = 1;          if (lua.lua_getmetatable(L, arg) &&  /* must have metatable */ -            (!(what & TAB_R) || checkfield(L, lua.to_luastring("__index", true), ++n)) && -            (!(what & TAB_W) || checkfield(L, lua.to_luastring("__newindex", true), ++n)) && -            (!(what & TAB_L) || checkfield(L, lua.to_luastring("__len", true), ++n))) { +            (!(what & TAB_R) || checkfield(L, to_luastring("__index", true), ++n)) && +            (!(what & TAB_W) || checkfield(L, to_luastring("__newindex", true), ++n)) && +            (!(what & TAB_L) || checkfield(L, to_luastring("__len", true), ++n))) {              lua.lua_pop(L, n);  /* pop metatable and tested metamethods */          }          else @@ -47,7 +47,7 @@ const aux_getn = function(L, n, w) {  const addfield = function(L, b, i) {      lua.lua_geti(L, 1, i);      if (!lua.lua_isstring(L, -1)) -        lauxlib.luaL_error(L, lua.to_luastring("invalid value (%s) at index %d in table for 'concat'"), +        lauxlib.luaL_error(L, to_luastring("invalid value (%s) at index %d in table for 'concat'"),              lauxlib.luaL_typename(L, -1), i);      lauxlib.luaL_addvalue(b); @@ -62,7 +62,7 @@ const tinsert = function(L) {              break;          case 3: {              pos = lauxlib.luaL_checkinteger(L, 2);  /* 2nd argument is the position */ -            lauxlib.luaL_argcheck(L, 1 <= pos && pos <= e, 2, lua.to_luastring("position out of bounds", true)); +            lauxlib.luaL_argcheck(L, 1 <= pos && pos <= e, 2, to_luastring("position out of bounds", true));              for (let i = e; i > pos; i--) {  /* move up elements */                  lua.lua_geti(L, 1, i - 1);                  lua.lua_seti(L, 1, i);  /* t[i] = t[i - 1] */ @@ -70,7 +70,7 @@ const tinsert = function(L) {              break;          }          default: { -            return lauxlib.luaL_error(L, lua.to_luastring("wrong number of arguments to 'insert'", true)); +            return lauxlib.luaL_error(L, to_luastring("wrong number of arguments to 'insert'", true));          }      } @@ -82,7 +82,7 @@ const tremove = function(L) {      let size = aux_getn(L, 1, TAB_RW);      let pos = lauxlib.luaL_optinteger(L, 2, size);      if (pos !== size)  /* validate 'pos' if given */ -        lauxlib.luaL_argcheck(L, 1 <= pos && pos <= size + 1, 1, lua.to_luastring("position out of bounds", true)); +        lauxlib.luaL_argcheck(L, 1 <= pos && pos <= size + 1, 1, to_luastring("position out of bounds", true));      lua.lua_geti(L, 1, pos);  /* result = t[pos] */      for (; pos < size; pos++) {          lua.lua_geti(L, 1, pos + 1); @@ -107,9 +107,9 @@ const tmove = function(L) {      checktab(L, 1, TAB_R);      checktab(L, tt, TAB_W);      if (e >= f) {  /* otherwise, nothing to move */ -        lauxlib.luaL_argcheck(L, f > 0 || e < luaconf.LUA_MAXINTEGER + f, 3, lua.to_luastring("too many elements to move", true)); +        lauxlib.luaL_argcheck(L, f > 0 || e < luaconf.LUA_MAXINTEGER + f, 3, to_luastring("too many elements to move", true));          let n = e - f + 1;  /* number of elements to move */ -        lauxlib.luaL_argcheck(L, t <= luaconf.LUA_MAXINTEGER - n + 1, 4, lua.to_luastring("destination wrap around", true)); +        lauxlib.luaL_argcheck(L, t <= luaconf.LUA_MAXINTEGER - n + 1, 4, to_luastring("destination wrap around", true));          if (t > e || t <= f || (tt !== 1 && lua.lua_compare(L, 1, tt, lua.LUA_OPEQ) !== 1)) {              for (let i = 0; i < n; i++) { @@ -130,7 +130,7 @@ const tmove = function(L) {  const tconcat = function(L) {      let last = aux_getn(L, 1, TAB_R); -    let sep = lauxlib.luaL_optlstring(L, 2, lua.to_luastring("")); +    let sep = lauxlib.luaL_optlstring(L, 2, to_luastring(""));      let lsep = sep.length;      let i = lauxlib.luaL_optinteger(L, 3, 1);      last = lauxlib.luaL_optinteger(L, 4, last); @@ -158,7 +158,7 @@ const pack = function(L) {      for (let i = n; i >= 1; i--)  /* assign elements */          lua.lua_seti(L, 1, i);      lua.lua_pushinteger(L, n); -    lua.lua_setfield(L, 1, lua.to_luastring("n"));  /* t.n = number of elements */ +    lua.lua_setfield(L, 1, to_luastring("n"));  /* t.n = number of elements */      return 1;  /* return table */  }; @@ -168,7 +168,7 @@ const unpack = function(L) {      if (i > e) return 0;  /* empty range */      let n = e - i;  /* number of elements minus 1 (avoid overflows) */      if (n >= Number.MAX_SAFE_INTEGER || !lua.lua_checkstack(L, ++n)) -        return lauxlib.luaL_error(L, lua.to_luastring("too many results to unpack", true)); +        return lauxlib.luaL_error(L, to_luastring("too many results to unpack", true));      for (; i < e; i++)  /* push arg[i..e - 1] (to avoid overflows) */          lua.lua_geti(L, 1, i);      lua.lua_geti(L, 1, e);  /* push last element */ @@ -208,14 +208,14 @@ const partition = function(L, lo, up) {          /* next loop: repeat ++i while a[i] < P */          while (lua.lua_geti(L, 1, ++i), sort_comp(L, -1, -2)) {              if (i == up - 1)  /* a[i] < P  but a[up - 1] == P  ?? */ -                lauxlib.luaL_error(L, lua.to_luastring("invalid order function for sorting")); +                lauxlib.luaL_error(L, to_luastring("invalid order function for sorting"));              lua.lua_pop(L, 1);  /* remove a[i] */          }          /* after the loop, a[i] >= P and a[lo .. i - 1] < P */          /* next loop: repeat --j while P < a[j] */          while (lua.lua_geti(L, 1, --j), sort_comp(L, -3, -1)) {              if (j < i)  /* j < i  but  a[j] > P ?? */ -                lauxlib.luaL_error(L, lua.to_luastring("invalid order function for sorting")); +                lauxlib.luaL_error(L, to_luastring("invalid order function for sorting"));              lua.lua_pop(L, 1);  /* remove a[j] */          }          /* after the loop, a[j] <= P and a[j + 1 .. up] >= P */ @@ -292,7 +292,7 @@ const auxsort = function(L, lo, up, rnd) {  const sort = function(L) {      let n = aux_getn(L, 1, TAB_RW);      if (n > 1) {  /* non-trivial interval? */ -        lauxlib.luaL_argcheck(L, n < luaconf.LUA_MAXINTEGER, 1, lua.to_luastring("array too big", true)); +        lauxlib.luaL_argcheck(L, n < luaconf.LUA_MAXINTEGER, 1, to_luastring("array too big", true));          if (!lua.lua_isnoneornil(L, 2))  /* is there a 2nd argument? */              lauxlib.luaL_checktype(L, 2, lua.LUA_TFUNCTION);  /* must be a function */          lua.lua_settop(L, 2);  /* make sure there are two arguments */ @@ -6,14 +6,6 @@ const ldebug = require("./ldebug.js");  const ldo    = require("./ldo.js");  const lstate = require("./lstate.js"); -module.exports.FENGARI_AUTHORS         = defs.FENGARI_AUTHORS; -module.exports.FENGARI_COPYRIGHT       = defs.FENGARI_COPYRIGHT; -module.exports.FENGARI_RELEASE         = defs.FENGARI_RELEASE; -module.exports.FENGARI_VERSION         = defs.FENGARI_VERSION; -module.exports.FENGARI_VERSION_MAJOR   = defs.FENGARI_VERSION_MAJOR; -module.exports.FENGARI_VERSION_MINOR   = defs.FENGARI_VERSION_MINOR; -module.exports.FENGARI_VERSION_NUM     = defs.FENGARI_VERSION_NUM; -module.exports.FENGARI_VERSION_RELEASE = defs.FENGARI_VERSION_RELEASE;  module.exports.LUA_AUTHORS             = defs.LUA_AUTHORS;  module.exports.LUA_COPYRIGHT           = defs.LUA_COPYRIGHT;  module.exports.LUA_ERRERR              = defs.thread_status.LUA_ERRERR; @@ -78,12 +70,6 @@ module.exports.LUA_VERSUFFIX           = defs.LUA_VERSUFFIX;  module.exports.LUA_YIELD               = defs.thread_status.LUA_YIELD;  module.exports.lua_Debug               = defs.lua_Debug;  module.exports.lua_upvalueindex        = defs.lua_upvalueindex; -module.exports.luastring_eq            = defs.luastring_eq; -module.exports.luastring_indexOf       = defs.luastring_indexOf; -module.exports.luastring_of            = defs.luastring_of; -module.exports.to_jsstring             = defs.to_jsstring; -module.exports.to_luastring            = defs.to_luastring; -module.exports.to_uristring            = defs.to_uristring;  module.exports.LUA_CDIR                = defs.LUA_CDIR;  module.exports.LUA_CPATH_DEFAULT       = defs.LUA_CPATH_DEFAULT;  module.exports.LUA_EXEC_DIR            = defs.LUA_EXEC_DIR; diff --git a/src/lutf8lib.js b/src/lutf8lib.js index 58533cf..9cf7f14 100644 --- a/src/lutf8lib.js +++ b/src/lutf8lib.js @@ -2,6 +2,7 @@  const lua     = require('./lua.js');  const lauxlib = require('./lauxlib.js'); +const {luastring_of, to_luastring} = require("./fengaricore.js");  const MAXUNICODE = 0x10FFFF; @@ -59,8 +60,8 @@ const utflen = function(L) {      let posi = u_posrelat(lauxlib.luaL_optinteger(L, 2, 1), len);      let posj = u_posrelat(lauxlib.luaL_optinteger(L, 3, -1), len); -    lauxlib.luaL_argcheck(L, 1 <= posi && --posi <= len, 2, lua.to_luastring("initial position out of string")); -    lauxlib.luaL_argcheck(L, --posj < len, 3, lua.to_luastring("final position out of string")); +    lauxlib.luaL_argcheck(L, 1 <= posi && --posi <= len, 2, to_luastring("initial position out of string")); +    lauxlib.luaL_argcheck(L, --posj < len, 3, to_luastring("final position out of string"));      while (posi <= posj) {          let dec = utf8_decode(s, posi); @@ -76,10 +77,10 @@ const utflen = function(L) {      return 1;  }; -const p_U = lua.to_luastring("%U"); +const p_U = to_luastring("%U");  const pushutfchar = function(L, arg) {      let code = lauxlib.luaL_checkinteger(L, arg); -    lauxlib.luaL_argcheck(L, 0 <= code && code <= MAXUNICODE, arg, lua.to_luastring("value out of range", true)); +    lauxlib.luaL_argcheck(L, 0 <= code && code <= MAXUNICODE, arg, to_luastring("value out of range", true));      lua.lua_pushfstring(L, p_U, code);  }; @@ -112,14 +113,14 @@ const byteoffset = function(L) {      let posi = n >= 0 ? 1 : s.length + 1;      posi = u_posrelat(lauxlib.luaL_optinteger(L, 3, posi), s.length); -    lauxlib.luaL_argcheck(L, 1 <= posi && --posi <= s.length, 3, lua.to_luastring("position out of range", true)); +    lauxlib.luaL_argcheck(L, 1 <= posi && --posi <= s.length, 3, to_luastring("position out of range", true));      if (n === 0) {          /* find beginning of current byte sequence */          while (posi > 0 && iscont(s[posi])) posi--;      } else {          if (iscont(s[posi])) -            lauxlib.luaL_error(L, lua.to_luastring("initial position is a continuation byte", true)); +            lauxlib.luaL_error(L, to_luastring("initial position is a continuation byte", true));          if (n < 0) {              while (n < 0 && posi > 0) {  /* move back */ @@ -156,19 +157,19 @@ const codepoint = function(L) {      let posi = u_posrelat(lauxlib.luaL_optinteger(L, 2, 1), s.length);      let pose = u_posrelat(lauxlib.luaL_optinteger(L, 3, posi), s.length); -    lauxlib.luaL_argcheck(L, posi >= 1, 2, lua.to_luastring("out of range", true)); -    lauxlib.luaL_argcheck(L, pose <= s.length, 3, lua.to_luastring("out of range", true)); +    lauxlib.luaL_argcheck(L, posi >= 1, 2, to_luastring("out of range", true)); +    lauxlib.luaL_argcheck(L, pose <= s.length, 3, to_luastring("out of range", true));      if (posi > pose) return 0;  /* empty interval; return no values */      if (pose - posi >= Number.MAX_SAFE_INTEGER) -        return lauxlib.luaL_error(L, lua.to_luastring("string slice too long", true)); +        return lauxlib.luaL_error(L, to_luastring("string slice too long", true));      let n = (pose - posi) + 1; -    lauxlib.luaL_checkstack(L, n, lua.to_luastring("string slice too long", true)); +    lauxlib.luaL_checkstack(L, n, to_luastring("string slice too long", true));      n = 0;      for (posi -= 1; posi < pose;) {          let dec = utf8_decode(s, posi);          if (dec === null) -            return lauxlib.luaL_error(L, lua.to_luastring("invalid UTF-8 code", true)); +            return lauxlib.luaL_error(L, to_luastring("invalid UTF-8 code", true));          lua.lua_pushinteger(L, dec.code);          posi = dec.pos;          n++; @@ -193,7 +194,7 @@ const iter_aux = function(L) {      else {          let dec = utf8_decode(s, n);          if (dec === null || iscont(s[dec.pos])) -            return lauxlib.luaL_error(L, lua.to_luastring("invalid UTF-8 code", true)); +            return lauxlib.luaL_error(L, to_luastring("invalid UTF-8 code", true));          lua.lua_pushinteger(L, n + 1);          lua.lua_pushinteger(L, dec.code);          return 2; @@ -217,12 +218,12 @@ const funcs = {  };  /* pattern to match a single UTF-8 character */ -const UTF8PATT = lua.luastring_of(91, 0, 45, 127, 194, 45, 244, 93, 91, 128, 45, 191, 93, 42); +const UTF8PATT = luastring_of(91, 0, 45, 127, 194, 45, 244, 93, 91, 128, 45, 191, 93, 42);  const luaopen_utf8 = function(L) {      lauxlib.luaL_newlib(L, funcs);      lua.lua_pushstring(L, UTF8PATT); -    lua.lua_setfield(L, -2, lua.to_luastring("charpattern", true)); +    lua.lua_setfield(L, -2, to_luastring("charpattern", true));      return 1;  };  | 
