Difference between revisions of "String exploding"

m (Added missing properties for the category page, the function itself "pollutes" lua's string table though.)
 
(12 intermediate revisions by 4 users not shown)
Line 6: Line 6:
 
     local o = {}
 
     local o = {}
 
     while true do
 
     while true do
         local pos = str:find(div)
+
         local pos1,pos2 = str:find(div)
         if not pos then
+
         if not pos1 then
 
             o[#o+1] = str
 
             o[#o+1] = str
 
             break
 
             break
 
         end
 
         end
         o[#o+1],str = str:sub(1,pos-1),str:sub(pos+#div)
+
         o[#o+1],str = str:sub(1,pos1-1),str:sub(pos2+1)
 
     end
 
     end
 
     return o
 
     return o
Line 29: Line 29:
 
print(original) --> foo bar
 
print(original) --> foo bar
 
</source>
 
</source>
 
 
[[Category:Snippets]]
 
[[Category:Snippets]]
 +
{{#set:LOVE Version=any}}
 +
{{#set:Description=Add the ability to explode strings. (return them as a table along defined divider substrings)}}

Latest revision as of 19:11, 11 November 2016

This function adds the ability to explode strings in Lua.

function string.explode(str, div)
    assert(type(str) == "string" and type(div) == "string", "invalid arguments")
    local o = {}
    while true do
        local pos1,pos2 = str:find(div)
        if not pos1 then
            o[#o+1] = str
            break
        end
        o[#o+1],str = str:sub(1,pos1-1),str:sub(pos2+1)
    end
    return o
end

Have an example:

tbl = string.explode("foo bar", " ")
print(tbl[1]) --> foo
-- since we added explode to the string table, we can also do this:
str = "foo bar"
tbl2 = str:explode(" ")
print(tbl2[2]) --> bar
-- to restore the original string, we can use Lua's table.concat:
original = table.concat(tbl, " ")
print(original) --> foo bar