| 1 |
-- remove whitespace at the ends of a string. |
| 2 |
function string:strip() |
| 3 |
return self:match'^%s*(.*%S)' or '' |
| 4 |
end |
| 5 |
|
| 6 |
-- split a string by a separator |
| 7 |
function string:split(sep) |
| 8 |
local sep, fields = sep or "\t", {} |
| 9 |
local pattern = string.format("[^%s]+", sep) |
| 10 |
for tok in self:gmatch(pattern) do fields[#fields+1] = tok end |
| 11 |
return fields |
| 12 |
end |
| 13 |
|
| 14 |
---------------------------------------------------- |
| 15 |
-- Testing Functions Don't copy these to Go code -- |
| 16 |
---------------------------------------------------- |
| 17 |
function test_strip() |
| 18 |
a = " aaa " |
| 19 |
assert(a:strip() == "aaa") |
| 20 |
a = " aaa\t" |
| 21 |
assert(a:strip() == "aaa") |
| 22 |
a = " aaa " |
| 23 |
assert(a:strip() == "aaa") |
| 24 |
end |
| 25 |
|
| 26 |
function test_split() |
| 27 |
v = string.split("x xx x", "%s") |
| 28 |
assert(#v == 3) |
| 29 |
assert(v[1] == "x") |
| 30 |
assert(v[2] == "xx") |
| 31 |
|
| 32 |
v = string.split("x xx\tx", "%s") |
| 33 |
assert(v[1] == "x") |
| 34 |
assert(v[2] == "xx") |
| 35 |
end |
| 36 |
|
| 37 |
|
| 38 |
function test() |
| 39 |
test_strip() |
| 40 |
test_split() |
| 41 |
end |
| 42 |
|
| 43 |
test() |