User.1
User.1

Reputation: 2642

Lua, Advancing to the next letter of the alphabet

I am very surprised that I did not find this explicitly answered here in StackOverflow, or on the Lua.org Website

If

Then, how do I manipulate that variable to change from, say, "J" to "K" ?

I looked at The String Library in the Lua.Org website, and didn't see the word "alphabet" on any of the pages there

e.g.

 --------------------------------------------------
 --                                              --
 --    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

Upvotes: 2

Views: 4264

Answers (1)

Mud
Mud

Reputation: 28991

I am very surprised that I did not find this explicitly answered here in StackOverflow, or on the Lua.org Website

It has to do with the character encodings used in your particular build of Lua, so it's beyond the scope of the Lua language proper.

You can use string.byte to get the byte(s) of a string. You can use string.char to turn bytes into a string.

Lua doesn't guarantee that the character codes for 'A' through 'Z' are contiguous, because C doesn't. You can't even be sure that each is encoded with a single byte. If your implementation is using ASCII then each character is represented by a single byte value and you can add 1 get the next letter, but you shouldn't rely on this. For example, if Temp_Letter < 'Z':

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

Here's a way to do this without relying on character encoding:

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

Upvotes: 5

Related Questions