From 9d78ee372d9d4db601098d4d302df48159d7b176 Mon Sep 17 00:00:00 2001 From: Benoit Giannangeli Date: Mon, 6 Mar 2017 11:15:22 +0100 Subject: string.rep --- README.md | 2 +- src/lstrlib.js | 10 ++++++++++ tests/lstrlib.js | 31 +++++++++++++++++++++++++++++++ 3 files changed, 42 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 8a1ba65..51c4b29 100644 --- a/README.md +++ b/README.md @@ -212,6 +212,7 @@ - [x] string.char - [x] string.len - [x] string.lower + - [x] string.rep - [x] string.upper - [ ] string.byte - [ ] string.dump @@ -222,7 +223,6 @@ - [ ] string.match - [ ] string.pack - [ ] string.packsize - - [ ] string.rep - [ ] string.reverse - [ ] string.sub - [ ] string.unpack diff --git a/src/lstrlib.js b/src/lstrlib.js index 96a33f5..11b266a 100644 --- a/src/lstrlib.js +++ b/src/lstrlib.js @@ -35,10 +35,20 @@ const str_upper = function(L) { return 1; }; +const str_rep = function(L) { + let s = lauxlib.luaL_checkstring(L, 1); + let n = lauxlib.luaL_checkinteger(L, 2); + let sep = lauxlib.luaL_optstring(L, 3, ""); + + lapi.lua_pushstring(L, (s + sep).repeat(n - 1) + s); + return 1; +}; + const strlib = { "char": str_char, "len": str_len, "lower": str_lower, + "rep": str_rep, "upper": str_upper }; diff --git a/tests/lstrlib.js b/tests/lstrlib.js index 7120525..56fa2a3 100644 --- a/tests/lstrlib.js +++ b/tests/lstrlib.js @@ -115,4 +115,35 @@ test('string.upper, string.lower', function (t) { "hello", "Correct element(s) on the stack" ); +}); + + +test('string.rep', function (t) { + let luaCode = ` + return string.rep("hello", 3, ", ") + `, L; + + t.plan(3); + + t.doesNotThrow(function () { + + L = lauxlib.luaL_newstate(); + + linit.luaL_openlibs(L); + + lauxlib.luaL_loadstring(L, luaCode); + + }, "Lua program loaded without error"); + + t.doesNotThrow(function () { + + lapi.lua_call(L, 0, -1); + + }, "Lua program ran without error"); + + t.strictEqual( + lapi.lua_tostring(L, -1), + "hello, hello, hello", + "Correct element(s) on the stack" + ); }); \ No newline at end of file -- cgit v1.2.3-70-g09d2