Module:String to array
Documentation for this module may be created at Module:String to array/doc
local p = {}
function string_to_array(Input_String, Separator)
local my_log ={}
if type(Input_String) ~= "string" then
return nil
end
if type(Separator) ~= "string" then
return nil
end
-- find the position of each separator in Input_String:
local separator_positions = {}
local next_start_position = 1
while next_start_position <= #Input_String do
ch1, ch2 = mw.ustring.find(Input_String, Separator, next_start_position)
if ch1 ~= nil then
table.insert(separator_positions, {ch1, ch2})
next_start_position = ch2 + 1
else
next_start_position = #Input_String + 1
end
end
-- To find the separated substrings, we need to group the beginning position of each Separator with the ending position
-- of the Separator that precedes it, so that we can extract the substring between them. For the first separator, the ending position of the
-- "preceding separator" is the beginning of the string. The last substring is bounded by the end of the string.
--
--
endchar = #Input_String
-- We are going to use a "for" statement to loop through the subtables of the separator_positions table.
count = 0
for i in ipairs(separator_positions) do
count = count + 1
end
--
substring_positions = {}
substring_positions[1] = {1, separator_positions[1][1] - 1}
for i = 2, count do
-- we should check that the table elements are not nil before attempting the assignment
if separator_positions[i][1] == nil then
-- report
elseif separator_positions[i - 1][2] == nil then
-- report
else
substring_positions[i] = {separator_positions[i - 1][2] + 1, separator_positions[i][1] - 1}
end
end
substring_positions[count + 1] = {separator_positions[count][2] + 1, endchar}
substrings = {}
for i, v in ipairs(substring_positions) do
substrings[i] = mw.ustring.sub(Input_String, v[1], v[2])
end
return substrings
end
return p