Lua - Split String
Splitting a string is the process in which we pass a regular expression or pattern with which one can split a given string into different parts.
In Lua, there is no split function that is present inside the standard library but we can make use of other functions to do the work that normally a split function would do.
A very simple example of a split function in Lua is to make use of the gmatch() function and then pass a pattern which we want to separate the string upon.
Example - Spliting Strings
Consider the example shown below −
main.lua
-- define a local variable local example = "lua is great" -- split string based on space for i in string.gmatch(example, "%S+") do -- print the substring print(i) end
Output
When we run the above code, we will get the following output−
lua is great
The above example works fine for simple patterns but when we want to make use of a regular expression and the case that we can have a default pattern with which to split, we can consider a more elegant example.
Example - Using regular expression
Consider the example shown below −
main.lua
-- define a function to spring a string with give separator
function mysplit (inputstr, sep)
-- if sep is null, set it as space
if sep == nil then
sep = '%s'
end
-- define an array
local t={}
-- split string based on sep
for str in string.gmatch(inputstr, '([^'..sep..']+)')
do
-- insert the substring in table
table.insert(t, str)
end
-- return the array
return t
end
-- split the string based on space
ans = mysplit('hey bro whats up?')
-- iterate through array of substrings
for _, v in ipairs(ans)
do
print(v)
end
-- split the string based on comma
-- iterate through array of substrings
ans = mysplit('x,y,z,m,n',',')
for _, v in ipairs(ans)
do
print(v)
end
Output
When we run the above code, we will get the following output−
hey bro whats up? x y z m n