Difference between revisions of "String exploding"

(Created page with 'This function adds the ability to explode strings in Lua. <source lang="lua"> function string.explode(str, div) local o = {} while true do local pos = str:find(d…')
 
Line 3: Line 3:
 
<source lang="lua">
 
<source lang="lua">
 
function string.explode(str, div)
 
function string.explode(str, div)
 +
    assert(type(str) == "string" and type(div) == "string", "invalid arguments")
 
     local o = {}
 
     local o = {}
 
     while true do
 
     while true do
Line 10: Line 11:
 
             break
 
             break
 
         end
 
         end
         o[#o+1],s = s:sub(1,pos-1),s:sub(pos+1)
+
         o[#o+1],str = str:sub(1,pos-1),str:sub(pos+#div)
 
     end
 
     end
 
     return o
 
     return o

Revision as of 18:54, 19 October 2010

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 pos = str:find(div)
        if not pos then
            o[#o+1] = str
            break
        end
        o[#o+1],str = str:sub(1,pos-1),str:sub(pos+#div)
    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