Minetest-WorldEditAdditions/worldeditadditions/utils/strings/split.lua
2021-06-02 21:29:36 -07:00

78 lines
2.2 KiB
Lua

-- Licence: GPLv2 (MPL-2.0 is compatible, so we can use this here)
-- Source: https://stackoverflow.com/a/43582076/1460422
-- gsplit: iterate over substrings in a string separated by a pattern
--
-- Parameters:
-- text (string) - the string to iterate over
-- pattern (string) - the separator pattern
-- plain (boolean) - if true (or truthy), pattern is interpreted as a plain
-- string, not a Lua pattern
--
-- Returns: iterator
--
-- Usage:
-- for substr in gsplit(text, pattern, plain) do
-- doSomething(substr)
-- end
function worldeditadditions.gsplit(text, pattern, plain)
local splitStart, length = 1, #text
return function ()
if splitStart then
local sepStart, sepEnd = string.find(text, pattern, splitStart, plain)
local ret
if not sepStart then
ret = string.sub(text, splitStart)
splitStart = nil
elseif sepEnd < sepStart then
-- Empty separator!
ret = string.sub(text, splitStart, sepStart)
if sepStart < length then
splitStart = sepStart + 1
else
splitStart = nil
end
else
ret = sepStart > splitStart and string.sub(text, splitStart, sepStart - 1) or ''
splitStart = sepEnd + 1
end
return ret
end
end
end
-- Split a string into substrings separated by a pattern.
-- @param text string The string to iterate over
-- @param pattern string The separator pattern
-- @param plain boolean If true (or truthy), pattern is interpreted as a
-- plain string, not a Lua pattern
-- @returns table A sequence table containing the substrings
function worldeditadditions.split(text, pattern, plain)
local ret = {}
for match in worldeditadditions.gsplit(text, pattern, plain) do
table.insert(ret, match)
end
return ret
end
-- Split into table of characters.
-- @param text string The string to iterate over
-- @param s bool Sort characters
-- @param d bool Remove duplicate characters
-- @returns table A sequence table containing the substrings
function worldeditadditions.tochars(text,s,d)
--function tochars(text,s,d)
t, set = {}, {}
if d then
text:gsub(".",function(c) set[c] = true end)
for k,v in pairs(set) do table.insert(t,k) end
else
text:gsub(".",function(c) table.insert(t,c) end)
end
if s then table.sort(t) end
return t
end