Extend the row table - how to do this? Is that even a good idea?

I am developing a Lua library in which I needed to smooth out the first letter of this line. So 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 

Originally it was an “internal” function, used only in my library.

Now I realized that my users will want to use this function in some cases.

Question 1 I’m thinking about expanding the table row, but I’m not sure how to proceed. Is this enough to do, or is there a more “lua-oriented” way?

 string.capitalize = function(s) ... etc etc (same code as above) 

Question 2 I wonder if this might even be a good idea for monkeypatch string. Should I provide a public capitalize function?

EDIT. In case anyone finds this in the future, a much more convenient capitalize function is shown on the string recipes page:

 str = str:gsub("^%l", string.upper) 
+6
string lua monkeypatching
source share
2 answers

I often make extensions for embedded tables. I do this primarily when I think that something is really important missing. Capitalization has not made my “important” list, but something called string.split has, for example.

When I do this, I follow the programming convention:

 require 'stringutil' -- load extra stuff into string.* require 'osutil' -- load extra stuff into os.* 

You get the idea.

Another thing that I do when I try to be sure that I am not overwriting something that does not exist yet, so that I can be confident in the future:

 function extend(tab, field, val) if tab[field] == nil then tab[field] = val return val elseif tab[field] ~= val then error(string.format('Extension %s.%s failed: already occupied by %s', nameof(tab), field, tostring(val))) else return val end end 

The nameof function looks like this:

 function nameof(val) for name, v in pairs(_G) do if v == val then return name end end return '?' end 

Final note: when I intend to share code with others, I try not to modify the predefined tables. According to the Golden Rule, this namespace is shared by everyone, and if I have other people using my code, it’s not fair for me to just take all the fields that I want in a predefined string table.

+6
source share

The answer to question 1 is yes. The answer to question 2 "is a matter of taste."

+2
source share

All Articles