Lua,前进到字母表的下一个字母



我很惊讶,我没有在StackOverflow或Lua.org网站上找到明确的答案

如果

  • 我的Lua变量包含一个字母,并且
  • 我想要字母表中的下一个字母

那么,我该如何操作这个变量,使其从"J"变为"K"呢?

我查看了Lua.Org网站上的字符串库,在的任何页面上都没有看到"字母表"这个词

例如

 --------------------------------------------------
 --                                              --
 --    Func Name: Alphabetic_Advance_By_1        --
 --                                              --
 --    On Entry:  The_Letter contains one        --
 --               character. It must be a        --
 --               letter in the alphabet.        --
 --                                              --
 --    On Exit:   The caller receives the        --
 --               next letter                    --
 --                                              --
 --               e.g.,                          --
 --                                              --
 --               A will return B                --
 --               B will return C                --
 --               C will return D                --
 --                                              --
 --               X will return Y                --
 --               Y will return Z                --
 --               Z will return A                --
 --                                              --
 --                                              --
 --                                              --
 --------------------------------------------------

 function Alphabetic_Advance_By_1(The_Letter)
 local Temp_Letter
 Temp_Letter = string.upper(The_Letter)
 -- okay, what goes here ???

 return(The_Answer)
 end

我很惊讶,我没有在StackOverflow或Lua.org网站上找到明确的答案

它与Lua的特定构建中使用的字符编码有关,因此它超出了Lua语言本身的范围。

您可以使用string.byte来获取字符串的字节。您可以使用string.char将字节转换为字符串。

Lua不能保证"A"到"Z"的字符代码是连续的,因为C不能。你甚至不能确定每一个都是用一个字节编码的。如果您的实现使用ASCII,那么每个字符都由一个单字节值表示,您可以加1得到下一个字母,但不应该依赖于此。例如,如果Temp_Letter<'Z':

 The_Answer = string.char(Temp_Letter:byte() + 1)

这里有一种不依赖字符编码的方法:

local alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
local index = alphabet:find(Temp_Letter)
if index then
    index = (index % #alphabet) + 1 -- move to next letter, wrapping at end
    TheAnswer = alphabet:sub(index, index)
end

相关内容

最新更新