I am developing a Lua library in which I needed to uppercase the first letter of a given string. Hence I created the following function:
local capitalize = function(s)
return string.gsub (s,
"(%w)([%w]*)",
function (first, rest)
return string.upper(first) .. rest
end,
1 )
end
This initially was an "internal" function, used only on my library.
Now I've realized that my users will want to use this function in some cases.
Question 1 I am thinking about extending the string table, but I am unsure about how to proceed. Is it enough to do this, or is there a more "lua-oriented" way?
string.capitalize = function(s)
... etc etc (same code as above)
Question 2 I wonder if it's even a good idea to monkeypatch string. Should I provide a public "capitalize" function instead?
EDIT - In case anyone finds this in the future, a far simpler "capitalize" function is shown on the string recipes page:
str = str:gsub("^%l", string.upper)