aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBenoit Giannangeli <benoit.giannangeli@boursorama.fr>2017-02-24 08:31:29 +0100
committerBenoit Giannangeli <benoit.giannangeli@boursorama.fr>2017-02-24 08:31:29 +0100
commitf52c86ef0450dd03ef9f2cd01143d6ed9ac759d1 (patch)
tree4ce0bd7cd6280b55a151ca4372e3665cc308ca7a
parentbd3ffd7282de8236cd4eb2ff2e21bbc10791bfeb (diff)
downloadfengari-f52c86ef0450dd03ef9f2cd01143d6ed9ac759d1.tar.gz
fengari-f52c86ef0450dd03ef9f2cd01143d6ed9ac759d1.tar.bz2
fengari-f52c86ef0450dd03ef9f2cd01143d6ed9ac759d1.zip
table.unpack
-rw-r--r--README.md2
-rw-r--r--src/ltablib.js16
-rw-r--r--tests/ltablib.js41
3 files changed, 57 insertions, 2 deletions
diff --git a/README.md b/README.md
index aafcec2..16d967a 100644
--- a/README.md
+++ b/README.md
@@ -206,11 +206,11 @@
- [ ] Table
- [x] table.concat
- [x] table.pack
+ - [x] table.unpack
- [ ] table.insert
- [ ] table.move
- [ ] table.remove
- [ ] table.sort
- - [ ] table.unpack
- [ ] Debug (errors)
- [ ] DOM API binding
- [ ] Parse Lua
diff --git a/src/ltablib.js b/src/ltablib.js
index ec7c578..86b57d7 100644
--- a/src/ltablib.js
+++ b/src/ltablib.js
@@ -91,9 +91,23 @@ const pack = function(L) {
return 1; /* return table */
};
+const unpack = function(L) {
+ let i = lauxlib.luaL_optinteger(L, 2, 1);
+ let e = lauxlib.luaL_opt(L, lauxlib.luaL_checkinteger, 3, lapi.lua_len(L, 1));
+ if (i > e) return 0; /* empty range */
+ let n = e - i; /* number of elements minus 1 (avoid overflows) */
+ if (n >= Number.MAX_SAFE_INTEGER || !lapi.lua_checkstack(L, ++n))
+ return lauxlib.luaL_error(L, "too many results to unpack");
+ for (; i < e; i++) /* push arg[i..e - 1] (to avoid overflows) */
+ lapi.lua_geti(L, 1, i);
+ lapi.lua_geti(L, 1, e); /* push last element */
+ return n;
+};
+
const tab_funcs = {
"concat": tconcat,
- "pack": pack
+ "pack": pack,
+ "unpack": unpack,
};
const luaopen_table = function(L) {
diff --git a/tests/ltablib.js b/tests/ltablib.js
index 28b9ce0..8221fe0 100644
--- a/tests/ltablib.js
+++ b/tests/ltablib.js
@@ -75,4 +75,45 @@ test('table.pack', function (t) {
[1, 2, 3],
"Correct element(s) on the stack"
);
+});
+
+
+test('table.unpack', function (t) {
+ let luaCode = `
+ return table.unpack({1, 2, 3, 4, 5}, 2, 4)
+ `, L;
+
+ t.plan(4);
+
+ t.doesNotThrow(function () {
+
+ let bc = toByteCode(luaCode).dataView;
+
+ L = lauxlib.luaL_newstate();
+
+ linit.luaL_openlibs(L);
+
+ lapi.lua_load(L, bc, "test-table.unpack");
+
+ lapi.lua_call(L, 0, -1);
+
+ }, "JS Lua program ran without error");
+
+ t.strictEqual(
+ lapi.lua_tointeger(L, -3),
+ 2,
+ "Correct element(s) on the stack"
+ );
+
+ t.strictEqual(
+ lapi.lua_tointeger(L, -2),
+ 3,
+ "Correct element(s) on the stack"
+ );
+
+ t.strictEqual(
+ lapi.lua_tointeger(L, -1),
+ 4,
+ "Correct element(s) on the stack"
+ );
}); \ No newline at end of file