lua實現split的簡易方法

 剛想用lua的split函數,網上查了下,實現都比較複雜,自己寫了個:)

string.split = function(s, p)

    local rt= {}
    string.gsub(s, '[^'..p..']+', function(w) table.insert(rt, w) end )
    return rt

end

 

使用例子一

local str = 'abc,123,hello,ok'

local list = string.split(str, ',')

for _, s in ipairs(list) do

    print(s)

end

 

結果:

abc

123

hello

ok

 

 

使用例子二

local str = 'abc \n123 \t hello ok'

local list = string.split(str, '%s')

for _, s in ipairs(list) do

    print(s)

end

 

結果:

abc

123

hello

ok

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章