如何迭代Lua字符串中的个人字符?(How to iterate individual characters in Lua string?)

编程入门 行业动态 更新时间:2024-10-27 00:27:11
如何迭代Lua字符串中的个人字符?(How to iterate individual characters in Lua string?)

我在Lua中有一个字符串,想要迭代它中的单个字符。 但没有我试过的代码,官方手册仅显示如何查找和替换子串:(

str = "abcd" for char in str do -- error print( char ) end for i = 1, str:len() do print( str[ i ] ) -- nil end

I have a string in Lua and want to iterate individual characters in it. But no code I've tried works and the official manual only shows how to find and replace substrings :(

str = "abcd" for char in str do -- error print( char ) end for i = 1, str:len() do print( str[ i ] ) -- nil end

最满意答案

在lua 5.1中,您可以通过几种方式迭代字符串的字符。

基本循环将是:

for i = 1, #str do local c = str:sub(i,i) -- do something with c end

但是,使用带有string.gmatch()的模式来获取迭代器可能会更有效:

for c in str:gmatch"." do -- do something with c end

或者甚至使用string.gsub()为每个字符调用一个函数:

str:gsub(".", function(c) -- do something with c end)

在上述所有方面,我已经利用了string模块被设置为所有字符串值的metatable,因此它的函数可以使用:符号作为成员调用。 我也使用(新到5.1,IIRC) #来获取字符串长度。

您的应用程序的最佳答案取决于很多因素,如果性能重要,基准是您的朋友。

您可能需要评估为什么需要迭代字符,并查看已经绑定到Lua的正则表达式模块之一,或者使用现代方法查看实现Lua的解析表达式语法的Roberto的lpeg模块。

In lua 5.1, you can iterate of the characters of a string this in a couple of ways.

The basic loop would be:

for i = 1, #str do local c = str:sub(i,i) -- do something with c end

But it may be more efficient to use a pattern with string.gmatch() to get an iterator over the characters:

for c in str:gmatch"." do -- do something with c end

Or even to use string.gsub() to call a function for each char:

str:gsub(".", function(c) -- do something with c end)

In all of the above, I've taken advantage of the fact that the string module is set as a metatable for all string values, so its functions can be called as members using the : notation. I've also used the (new to 5.1, IIRC) # to get the string length.

The best answer for your application depends on a lot of factors, and benchmarks are your friend if performance is going to matter.

You might want to evaluate why you need to iterate over the characters, and to look at one of the regular expression modules that have been bound to Lua, or for a modern approach look into Roberto's lpeg module which implements Parsing Expression Grammers for Lua.

更多推荐

本文发布于:2023-08-07 03:18:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1459592.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   字符   迭代   Lua   string

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!