DX Unified Infrastructure Management

  • 1.  Lua split command

    Posted Sep 19, 2012 06:29 AM

    Hello

     

    I have to split a string which can contail empty values, like "a,,b,c,".

    The split command 'split("a,,b,c,",",")' returns
    1: a

    2: b

    3: c

     

    I need it to be

    1: a

    2:

    3: b

    4: c

     

    How can I handle that?

     

    Thanks

    Leandro



  • 2.  Re: Lua split command
    Best Answer

    Posted Sep 19, 2012 07:35 AM

    Hi,

     

    I think split leaves out empty values by design. You'd have to create a custom function. Here's some good info on the subject: http://lua-users.org/wiki/SplitJoin

     

    From the same page, here's a custom function that does the trick:

    function Split(str, delim, maxNb)
        -- Eliminate bad cases...
        if string.find(str, delim) == nil then
            return { str }
        end
        if maxNb == nil or maxNb < 1 then
            maxNb = 0    -- No limit
        end
        local result = {}
        local pat = "(.-)" .. delim .. "()"
        local nb = 0
        local lastPos
        for part, pos in string.gfind(str, pat) do
            nb = nb + 1
            result[nb] = part
            lastPos = pos
            if nb == maxNb then break end
        end
        -- Handle the last field
        if nb ~= maxNb then
            result[nb + 1] = string.sub(str, lastPos)
        end
        return result
    end

     



  • 3.  Re: Lua split command

    Posted Sep 19, 2012 07:56 AM
    The function works perfect!
    Thanks