From bd3ffd7282de8236cd4eb2ff2e21bbc10791bfeb Mon Sep 17 00:00:00 2001 From: Benoit Giannangeli Date: Fri, 24 Feb 2017 08:13:38 +0100 Subject: table.pack --- src/lapi.js | 8 ++++++++ src/ltablib.js | 14 +++++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/lapi.js b/src/lapi.js index 6316326..f34216b 100644 --- a/src/lapi.js +++ b/src/lapi.js @@ -355,6 +355,13 @@ const lua_setfield = function(L, idx, k) { auxsetstr(L, index2addr(L, idx), k) }; +const lua_seti = function(L, idx, n) { + assert(1 < L.top - L.ci.funcOff, "not enough elements in the stack"); + let t = index2addr(L, idx); + lvm.settable(L, t, n, L.stack[L.top - 1]); + L.top--; /* pop value */ +}; + const lua_rawset = function(L, idx) { assert(2 < L.top - L.ci.funcOff, "not enough elements in the stack"); let o = index2addr(L, idx); @@ -780,6 +787,7 @@ module.exports.lua_remove = lua_remove; module.exports.lua_rotate = lua_rotate; module.exports.lua_setfield = lua_setfield; module.exports.lua_setglobal = lua_setglobal; +module.exports.lua_seti = lua_seti; module.exports.lua_setmetatable = lua_setmetatable; module.exports.lua_settable = lua_settable; module.exports.lua_settop = lua_settop; diff --git a/src/ltablib.js b/src/ltablib.js index 8e1f758..ec7c578 100644 --- a/src/ltablib.js +++ b/src/ltablib.js @@ -80,8 +80,20 @@ const tconcat = function(L) { return 1; }; +const pack = function(L) { + let n = lapi.lua_gettop(L); /* number of elements to pack */ + lapi.lua_createtable(L, n, 1); /* create result table */ + lapi.lua_insert(L, 1); /* put it at index 1 */ + for (let i = n; i >= 1; i--) /* assign elements */ + lapi.lua_seti(L, 1, i); + lapi.lua_pushinteger(L, n); + lapi.lua_setfield(L, 1, "n"); /* t.n = number of elements */ + return 1; /* return table */ +}; + const tab_funcs = { - "concat": tconcat + "concat": tconcat, + "pack": pack }; const luaopen_table = function(L) { -- cgit v1.2.3-70-g09d2