Lua 中这个函数在做什么?

function splitSat(str, pat, max, regex)
    pat = pat or "\n" --Patron de búsqueda
    max = max or #str

    local t = {}
    local c = 1

    if #str == 0 then
            return {""}
    end

    if #pat == 0 then
            return nil
    end

    if max == 0 then
            return str
    end

    repeat
            local s, e = str:find(pat, c, not regex)     -- 在字符串 str 中,从位置 c 开始查找模式 pat
                                                         -- 将起始位置保存为 s,结束位置保存为 e
            max = max - 1
            if s and max < 0 then
                    if #(str:sub(c)) > 0 then           -- 如果从 c 开始的字符串片段的长度大于 0
                            t[#t+1] = str:sub(c)
                    else                                                                                                                                                                                     values
                            t[#t+1] = ""    -- 创建带有空值的表
                    end
            else
                    if #(str:sub(c, s and s - 1)) > 0 then          -- 如果从 c 到 s 之间的字符串片段的长度大于 0
                            t[#t+1] = str:sub(c, s and s - 1)
                    else
                            t[#t+1] = ""            -- 创建带有空值的表
                    end
            end
            c = e and e + 1 or #str + 1
    until not s or max < 0

    return t
    end

我想知道这个函数在干什么。我知道它会将一个字符串和一个模式组成一种表。特别是我想知道 *t[#t+1] = str:sub(c, s and s - 1)* 做了什么。

点赞
用户4984564
用户4984564

从我所了解的来看,它会将一个长字符串分成与某个模式匹配的子字符串,并忽略模式匹配之间的所有内容。例如,它可能将字符串 11aa22 匹配到模式\d\d,得出表["11", "22"]

t[#t+1] = <something>在表t的末尾插入一个值,它等同于table.insert(t, <something>)

#t返回一个数组的长度(即具有连续数字索引的表),例如 #[1, 2, 3] 等于 3

str:sub(c, s and s - 1)利用了luas的许多功能。s and s - 1如果s不为nil,则计算为s-1,否则为空。如果snil,则只有s-1会抛出错误。

  • 10 and 10 - 1等于9
  • 10 - 1等于9
  • nil and nil - 1等于nil
  • nil - 1 -> 会抛出错误

str:sub(a, b)只是返回以a为起始索引和b为终止索引的子字符串(其中ab是数字索引)

("abcde"):sub(2,4)等于"bcd"

2017-11-07 15:33:59