function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern,function (c)fields[#fields + 1] = c end)
print(c)
return fields
end
I have above block of code.
string.format
function has separator as its second argument. Why is that? We generally have the blob of text as second argument which needs to be formatted.
gsub
function usually replace a given pattern. what is he role of function(c)
in gsub
? How is it being called and used here? Where is c
coming from in function(c)
?
In the example code, the format specifier of string.format()
is "([^%s]+)"
, in which %s
expects a string, thus the second argument sep
is a string.
For instance, if sep
has a value of ","
, then pattern
becomes ([^,]+)
(one or more occurrences of non-commas), which means the function string:split
is splitting strings by commas (,
)
string.gsub()
can take three types as the second argument, a string, a function, or a table. When it's a function, it is called every time a match occurs, with all captured substrings passed as arguments, in order. For more details, see string.gsub()
.