“延长” “字符串”表-怎么做呢?这是个好主意吗?
我正在开发一个 Lua 库,其中我需要将给定字符串的第一个字母大写。因此,我创建了以下函数:
local capitalize = function(s)
return string.gsub (s,
"(%w)([%w]*)",
function (first, rest)
return string.upper(first) .. rest
end,
1 )
end
这最初是一个“内部”函数,仅在我的库上使用。
现在我意识到我的用户在某些情况下会想要使用此功能。
问题1 我正在考虑扩展字符串表,但我不确定如何继续。这样做就足够了,还是有更“面向lua”的方式?
string.capitalize = function(s)
... etc etc (same code as above)
问题2 我想知道对字符串进行猴子补丁是否是个好主意。我应该提供公共“大写”功能吗?
编辑 - 如果将来有人发现这个,字符串食谱上会显示一个更简单的“大写”函数 页面:
str = str:gsub("^%l", string.upper)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我经常对内置表进行扩展。我这样做主要是当我认为缺少一些真正重要的东西时。大写字母并没有出现在我的“重要”列表中,但是一个名为
string.split
的东西却出现在我的“重要”列表中。当我这样做时,我遵循一个编程约定:
你明白了。
当我小心的时候我做的另一件事是确保我不会覆盖不存在的东西,这样我就可以面向未来:
nameof
函数是这样的:最后注意:当我打算与其他人共享代码时,我倾向于不修改预定义的表。根据黄金法则,该命名空间是由每个人共享的,如果我想让其他人使用我的代码,那么仅仅在预定义的
string
中获取我想要的任何字段对我来说是不公平的桌子。I frequently make extensions to builtin tables. I do this primarily when I think something really important is missing. Capitalization hasn't made my "important" list, but something called
string.split
has, for example.When I do this I follow a programming convention:
You get the idea.
The other thing I do when I'm being careful is make sure I don't overwrite something that isn't already there, so that I'm future-proofed:
The
nameof
function is like this:Final note: when I intend to share code with others, I tend not to modify the predefined tables. According to the Golden Rule, that namespace is shared by everybody, and if I'm going to have other people using my code, it's not fair for me just to grab whatever fields I want in the predefined
string
table.问题1的答案是“是”。问题2的答案是“这是一个品味问题”。
The answer to Question 1 is "yes". The answer to Question 2 is "it's a matter of taste".