Skip to content

Commit

Permalink
string: introduce string.strip
Browse files Browse the repository at this point in the history
* Add support of string.strip, string.lstrip, string.rstrip

Closes #2785
  • Loading branch information
ilmarkov authored and rtsisyk committed Oct 31, 2017
1 parent c383806 commit 6007e6d
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
25 changes: 25 additions & 0 deletions src/lua/string.lua
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,28 @@ local function string_hex(inp)
return ffi.string(res, len)
end

local function string_strip(inp)
if type(inp) ~= 'string' then
error(err_string_arg:format(1, "string.strip", 'string', type(inp)), 2)
end
return (string.gsub(inp, "^%s*(.-)%s*$", "%1"))
end

local function string_lstrip(inp)
if type(inp) ~= 'string' then
error(err_string_arg:format(1, "string.lstrip", 'string', type(inp)), 2)
end
return (string.gsub(inp, "^%s*(.-)", "%1"))
end

local function string_rstrip(inp)
if type(inp) ~= 'string' then
error(err_string_arg:format(1, "string.rstrip", 'string', type(inp)), 2)
end
return (string.gsub(inp, "(.-)%s*$", "%1"))
end


-- It'll automatically set string methods, too.
local string = require('string')
string.split = string_split
Expand All @@ -301,3 +323,6 @@ string.center = string_center
string.startswith = string_startswith
string.endswith = string_endswith
string.hex = string_hex
string.strip = string_strip
string.lstrip = string_lstrip
string.rstrip = string_rstrip
16 changes: 15 additions & 1 deletion test/app-tap/string.test.lua
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
local tap = require('tap')
local test = tap.test("string extensions")

test:plan(4)
test:plan(5)

test:test("split", function(test)
test:plan(10)
Expand Down Expand Up @@ -114,4 +114,18 @@ test:test("hex", function(test)
test:is(string.hex(""), "", "hex empty string")
end)

test:test("strip", function(test)
test:plan(6)
local str = " hello hello "
test:is(string.len(string.strip(str)), 11, "strip")
test:is(string.len(string.lstrip(str)), 12, "lstrip")
test:is(string.len(string.rstrip(str)), 13, "rstrip")
local _, err = pcall(string.strip, 12)
test:ok(err and err:match("%(string expected, got number%)"))
_, err = pcall(string.lstrip, 12)
test:ok(err and err:match("%(string expected, got number%)"))
_, err = pcall(string.rstrip, 12)
test:ok(err and err:match("%(string expected, got number%)"))
end )

os.exit(test:check() == true and 0 or -1)

0 comments on commit 6007e6d

Please sign in to comment.