使用 string.gsub 最有效地将 x 更改为 y (Lua)

发布于 2024-12-08 19:54:13 字数 642 浏览 3 评论 0原文

尽管我对 Lua 中的 gsub 越来越熟悉,但我在这里很茫然。可能有一种更好的方法可以更有效地做到这一点,这就是我正在寻找的。我想做的是改变:

\(port Planes)9e;\(enter pool)n2euw

变成

port Planes;run 9e;enter pool;run n2euw

这似乎是一件简单的事情,但我完全一片空白。我或许可以将其部分归因于精疲力尽,但这并不是一个真正的借口。我的方式是:

string.gsub(variable, ";","\(")
string.gsub(variable, "\(", ";")
string.gsub(variable, ")",";run")
string.gsub(variable, ";;",";")

但对我来说,这看起来相当草率,而且没有我希望的那么有效。如果“)”结束该行,并且它会放置“;”,它也会带来问题。在那里,这不是我想要的。我希望能有更熟悉 Lua 的人提供专业知识来整理这个问题并提高效率。一旦一切都说完并完成后,我将把它放入一个函数中。谢谢!

编辑:经过测试,它甚至不起作用,无论如何......而且我无法找出正确的模式匹配序列来使其起作用......

I'm at a loss here, though I've been getting more and more familiar with gsub in Lua. There probably is a better way to do this more efficiently, and that's what I'm looking for. What I'm wishing to do is change:

\(port Planes)9e;\(enter pool)n2euw

into

port Planes;run 9e;enter pool;run n2euw

It seems like it would be a simple thing, but I'm totally drawing a blank. I could probably attribute that partly to being exhausted, but that's not really an excuse. The way I would have it is:

string.gsub(variable, ";","\(")
string.gsub(variable, "\(", ";")
string.gsub(variable, ")",";run")
string.gsub(variable, ";;",";")

But to me, that looks pretty sloppy, and not as efficient as I would like it to me. It also poses the problem if ")" ends the line, and it'd put ";" there, which is not something I want. I would appreciate the expertise of someone more familiar with Lua who can tidy this up and make it more efficient. I'll be putting it into a function once all is said and done. Thanks!

Edit: Upon testing that, it doesn't even work, anyway... and I can't figure out the proper pattern matching sequence to use to make it work at all...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧瑾黎汐 2024-12-15 19:54:13

在不了解更多可能的组合的情况下,我不能说这在每个实例中都有效,但它应该开始:

string.gsub(variable,"\\%((.-)%)","%1;run ")
string.gsub(variable,";run $","")

第一个 gsub 返回括号内的命令,删除括号并添加 ';run '在最后。

第二个是检查字符串的结尾是否为“;run”,如果是则替换它。

您还应该查看这篇文章,了解关于模式的精彩总结:
http://www.lua.org/pil/20.2.html

Without knowing more about the possible combinations you could have, I can't say that this would work in every instance but it should give a start:

string.gsub(variable,"\\%((.-)%)","%1;run ")
string.gsub(variable,";run $","")

The first gsub is returning the commands inside your parenthesis, removing the parenthesis and adding ';run ' at the end.

The second one is checking whether the end of the string is ';run ' and replacing it if that's the case.

You should also check out this article for a nice summary on patterns:
http://www.lua.org/pil/20.2.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文