summaryrefslogtreecommitdiff
path: root/src/ltablib.js
diff options
context:
space:
mode:
authorBenoit Giannangeli <benoit.giannangeli@boursorama.fr>2017-02-24 08:52:06 +0100
committerBenoit Giannangeli <benoit.giannangeli@boursorama.fr>2017-02-24 09:00:48 +0100
commitae4e53e2e7234a167058199085921a9182e8522a (patch)
treeedf216c29fd494397c8b27e8088298677db01046 /src/ltablib.js
parentf52c86ef0450dd03ef9f2cd01143d6ed9ac759d1 (diff)
downloadfengari-ae4e53e2e7234a167058199085921a9182e8522a.tar.gz
fengari-ae4e53e2e7234a167058199085921a9182e8522a.tar.bz2
fengari-ae4e53e2e7234a167058199085921a9182e8522a.zip
table.insert
Diffstat (limited to 'src/ltablib.js')
-rw-r--r--src/ltablib.js30
1 files changed, 28 insertions, 2 deletions
diff --git a/src/ltablib.js b/src/ltablib.js
index 86b57d7..8ea6f08 100644
--- a/src/ltablib.js
+++ b/src/ltablib.js
@@ -47,7 +47,7 @@ const checktab = function(L, arg, what) {
const aux_getn = function(L, n, w) {
checktab(L, n, w | TAB_L);
- lauxlib.luaL_len(L, n);
+ return lauxlib.luaL_len(L, n);
};
const addfield = function(L, b, i) {
@@ -58,6 +58,31 @@ const addfield = function(L, b, i) {
lauxlib.luaL_addvalue(b);
};
+const tinsert = function(L) {
+ let e = aux_getn(L, 1, TAB_RW) + 1; /* first empty element */
+ let pos;
+ switch (lapi.lua_gettop(L)) {
+ case 2:
+ pos = e;
+ break;
+ case 3: {
+ pos = lauxlib.luaL_checkinteger(L, 2); /* 2nd argument is the position */
+ lauxlib.luaL_argcheck(L, 1 <= pos && pos <= e, 2, "position out of bounds");
+ for (let i = e; i > pos; i--) { /* move up elements */
+ lapi.lua_geti(L, 1, i - 1);
+ lapi.lua_seti(L, 1, i); /* t[i] = t[i - 1] */
+ }
+ break;
+ }
+ default: {
+ return lauxlib.luaL_error(L, "wrong number of arguments to 'insert'");
+ }
+ }
+
+ lapi.lua_seti(L, 1, pos); /* t[pos] = v */
+ return 0;
+};
+
const tconcat = function(L) {
let last = aux_getn(L, 1, TAB_R);
let sep = lauxlib.luaL_optlstring(L, 2, "");
@@ -106,8 +131,9 @@ const unpack = function(L) {
const tab_funcs = {
"concat": tconcat,
+ "insert": tinsert,
"pack": pack,
- "unpack": unpack,
+ "unpack": unpack
};
const luaopen_table = function(L) {