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

查看:130
本文介绍了如何迭代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中,您可以通过两种方法来迭代字符串的字符.

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模块被设置为所有字符串值的元表,因此可以使用:表示法将其功能称为成员.我还使用了(对IIRC来说是5.1的新功能)#来获取字符串长度.

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/~roberto/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天全站免登陆