如何迭代Lua字符串中的单个字符? [英] How to iterate individual characters in Lua string?

查看:32
本文介绍了如何迭代Lua字符串中的单个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Lua 中有一个字符串,想迭代其中的单个字符.但是我试过的代码都没有,官方手册只展示了如何查找和替换子字符串:(

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 中,您可以通过多种方式迭代字符串 this 的字符.

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

基本循环是:

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

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

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

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

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

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

在上述所有内容中,我利用了 string 模块被设置为所有字符串值的元表这一事实,因此可以使用 : 符号.我还使用了(新的 5.1,IIRC)# 来获取字符串长度.

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.

您可能想评估为什么您需要迭代字符,并查看绑定到 Lua 的正则表达式模块之一,或者查看 Roberto 的 为什么一个 href="http://www.inf.puc-rio.br/%7Eroberto/lpeg.html" rel="noreferrer">lpeg 模块,它实现了 Lua 的解析表达式语法.

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.

这篇关于如何迭代Lua字符串中的单个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆