aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorBenoit Giannangeli <benoit.giannangeli@boursorama.fr>2017-02-22 13:35:01 +0100
committerBenoit Giannangeli <benoit.giannangeli@boursorama.fr>2017-02-22 13:35:01 +0100
commit290ec54e13d1dff301465cbfa2fd7b4e1e52962f (patch)
treeac1d4988da8cd15b567891294bf1ac94af90242d /src
parenta40719dc74b8dbb0d6c8fc0272c0d79ad8a7a9ea (diff)
downloadfengari-290ec54e13d1dff301465cbfa2fd7b4e1e52962f.tar.gz
fengari-290ec54e13d1dff301465cbfa2fd7b4e1e52962f.tar.bz2
fengari-290ec54e13d1dff301465cbfa2fd7b4e1e52962f.zip
lua_stringtonumber, tonumber
Diffstat (limited to 'src')
-rw-r--r--src/lapi.js10
-rw-r--r--src/lbaselib.js28
2 files changed, 37 insertions, 1 deletions
diff --git a/src/lapi.js b/src/lapi.js
index bc4dd54..19e3090 100644
--- a/src/lapi.js
+++ b/src/lapi.js
@@ -488,6 +488,13 @@ const lua_topointer = function(L, idx) {
}
};
+const lua_stringtonumber = function(L, s) {
+ let number = parseFloat(s);
+ L.stack[L.top++] = new TValue(number % 1 !== 0 ? CT.LUA_TNUMFLT : CT.LUA_TNUMINT, number);
+ assert(L.top <= L.ci.top, "stack overflow");
+ return s.length;
+};
+
const f_call = function(L, ud) {
ldo.luaD_callnoyield(L, ud.funcOff, ud.nresults);
};
@@ -705,4 +712,5 @@ module.exports.lua_error = lua_error;
module.exports.lua_insert = lua_insert;
module.exports.lua_gc = lua_gc;
module.exports.lua_getallocf = lua_getallocf;
-module.exports.lua_getextraspace = lua_getextraspace; \ No newline at end of file
+module.exports.lua_getextraspace = lua_getextraspace;
+module.exports.lua_stringtonumber = lua_stringtonumber; \ No newline at end of file
diff --git a/src/lbaselib.js b/src/lbaselib.js
index 19a990e..9cc4fb1 100644
--- a/src/lbaselib.js
+++ b/src/lbaselib.js
@@ -127,6 +127,33 @@ const luaB_ipairs = function(L) {
return 3;
};
+const luaB_tonumber = function(L) {
+ if (lapi.lua_type(L, 2) <= 0) { /* standard conversion? */
+ lauxlib.luaL_checkany(L, 1);
+ if (lapi.lua_type(L, 1) === CT.LUA_TNUMBER) { /* already a number? */
+ lapi.lua_settop(L, 1);
+ return 1;
+ } else {
+ let s = lapi.lua_tostring(L, 1);
+ if (s !== null && lapi.lua_stringtonumber(L, s) === s.length)
+ return 1; /* successful conversion to number */
+ }
+ } else {
+ let base = lauxlib.luaL_checkinteger(L, 2);
+ lauxlib.luaL_checktype(L, 1, CT.LUA_TSTRING); /* no numbers as strings */
+ let s = lapi.lua_tostring(L, 1);
+ lauxlib.luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range");
+ let n = parseInt(s, base);
+ if (!isNaN(n)) {
+ lapi.lua_pushinteger(L, n);
+ return 1;
+ }
+ }
+
+ lapi.lua_pushnil(L);
+ return 1;
+};
+
const luaB_error = function(L) {
let level = lauxlib.luaL_optinteger(L, 2, 1);
lapi.lua_settop(L, 1);
@@ -195,6 +222,7 @@ const base_funcs = {
"collectgarbage": function () {},
"print": luaB_print,
"tostring": luaB_tostring,
+ "tonumber": luaB_tonumber,
"getmetatable": luaB_getmetatable,
"ipairs": luaB_ipairs,
"select": luaB_select,