Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0125-preview· OpenAIAi2 WildChat-4.8M (AI2)

Write Lua function to split string by character. For example: split("abc-def", "-") will…

  1. User

    Write Lua function to split string by character. For example: split("abc-def", "-") will return table {"abc", "def"}

  2. Assistant

    To create a Lua function that splits a string by a specified character (or pattern) and returns a table containing the split parts, you can use the string.gmatch function in combination with the pattern matching capabilities of Lua. Lua patterns can be used to specify the delimiter. Here's how you could write such a function:

    function split(inputstr, sep)
        if sep == nil then
            sep = "%s"
        end
        local t={}
        for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
            table.insert(t, str)
        end
        return t
    end
    
    -- Example Usage
    local result = split("abc-def", "-")
    for i, v in ipairs(result) do
        print(i, v)
    end
    

    This split function takes an input string inputstr and a separator sep. The separator sep is used in a pattern that matches sequences of characters that are not the separator. Each matched sequence is added to a table t, which is then returned.

    The if sep == nil then sep = "%s" end line ensures that if no separator is provided, whitespace (%s) is used as the default separator. This is compliant with the behavior of similar functions in many other languages and environments.

    Note: When dealing with special pattern characters as separators (such as ".", "-", "*", "?", etc.), this function works correctly because it directly uses the separator inside a negated character class pattern ([^"..sep.."]+). However, if you intend to use patterns as separators, or if the separator needs to be dynamically built from pattern special characters, it might require escaping specific characters for the pattern to work as intended.

    The example usage demonstrates splitting the string "abc-def" by the delimiter "-", and then iterating over the resulting table to print its contents.