From 26acf1752df58c565b349cf4c6963a2d18950a36 Mon Sep 17 00:00:00 2001 From: Max Cahill <1bardesign@gmail.com> Date: Fri, 17 Apr 2020 10:35:00 +1000 Subject: [PATCH] [added] stringx module (just split for now) and overlay to string on export --- init.lua | 10 +++++++++- stringx.lua | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 stringx.lua diff --git a/init.lua b/init.lua index 1afd3b3..349b690 100644 --- a/init.lua +++ b/init.lua @@ -34,6 +34,8 @@ local _stable_sort = require_relative("stable_sort") local _functional = require_relative("functional") local _sequence = require_relative("sequence") +local _stringx = require_relative("stringx") + local _vec2 = require_relative("vec2") local _vec3 = require_relative("vec3") local _intersect = require_relative("intersect") @@ -59,6 +61,9 @@ local _batteries = { -- table = _tablex, tablex = _tablex, + -- + string = _stringx, + stringx = _stringx, --sorting routines stable_sort = _stable_sort, sort = _stable_sort, @@ -66,7 +71,7 @@ local _batteries = { functional = _functional, -- sequence = _sequence, - -- + --geom vec2 = _vec2, vec3 = _vec3, intersect = _intersect, @@ -98,6 +103,9 @@ function _batteries:export(self) --overlay onto math _tablex.overlay(math, _mathx) + --overlay onto string + _tablex.overlay(string, _stringx) + --export geom vec2 = _vec2 vec3 = _vec3 diff --git a/stringx.lua b/stringx.lua new file mode 100644 index 0000000..e98ece1 --- /dev/null +++ b/stringx.lua @@ -0,0 +1,53 @@ +--[[ + extra string routines +]] + +local stringx = setmetatable({}, { + __index = string +}) + +--split a string on a delimiter into an ordered table +function stringx:split(delim) + --try to create as little garbage as possible! + --one table to contain the result, plus the split strings should be all we need + --as such we work with the bytes underlying the string, as string.find is not compiled on older luajit :) + local length = self:len() + -- + local delim_length = delim:len() + local delim_start = delim:byte(1) + --iterate through and collect split sites + local res = {} + local i = 1 + while i <= length do + --scan for delimiter + if self:byte(i) == delim_start then + local has_whole_delim = true + for j = 2, delim_length do + if self:byte(i + j - 1) ~= delim:byte(j) then + has_whole_delim = false + break + end + end + if has_whole_delim then + table.insert(res, i) + end + --iterate forward + i = i + delim_length + else + --iterate forward + i = i + 1 + end + end + --re-iterate, collecting substrings + i = 1 + for si, j in ipairs(res) do + res[si] = self:sub(i, j-1) + i = j + delim_length + end + --add the final section + table.insert(res, self:sub(i, -1)) + --return the collection + return res +end + +return stringx