Write Lua function to split string by character. For example: split("abc-def", "-") will…
- User
Write Lua function to split string by character. For example: split("abc-def", "-") will return table {"abc", "def"}
- 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.gmatchfunction 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) endThis
splitfunction takes an input stringinputstrand a separatorsep. The separatorsepis used in a pattern that matches sequences of characters that are not the separator. Each matched sequence is added to a tablet, which is then returned.The
if sep == nil then sep = "%s" endline 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.