Alexwall
Alexwall

Reputation: 667

Converting a number to its alphabetical counterpart in lua

I am trying to make a lua script that takes an input of numbers seperated by commas, and turns them into letters, so 1 = a ect, however I have not found a way to do this easily because the string libray outputs a = 97, so I have no clue where to go now, any help?

Upvotes: 10

Views: 18632

Answers (4)

Veer Singh
Veer Singh

Reputation: 963

Merely just account for the starting value of a-z in the ascii table.

function convert(...)
    local ar = {...}
    local con = {}
    for i,v in pairs(ar) do
        table.insert(con, ("").char(v+96))
    end
    return con;
end

for i,v in pairs(convert(1,2,3,4)) do
    print(v)
end

Upvotes: 2

warspyking
warspyking

Reputation: 3113

Alternatively to these answers, you could store each letter in a table and simply index the table:

local letters = {'a','b','c'} --Finish

print(letters[1], letters[2], letters[3])

Upvotes: 1

Paul Kulchenko
Paul Kulchenko

Reputation: 26774

You can use string.byte and string.char functions:

string.char(97) == "a"
string.byte("a") == 97

If you want to start from "a" (97), then just subtract that number:

local function ord(char)
  return string.byte(char)-string.byte("a")+1
end

This will return 1 for "a", 2 for "b" and so on. You can make it handle "A", "B" and others in a similar way.

If you need number-to-char, then something like this may work:

local function char(num)
  return string.char(string.byte("a")+num-1)
end

Upvotes: 12

lhf
lhf

Reputation: 72342

Define your encoding as follows:

encoding = [[abc...]]

in whatever order you want. Then use it as follows

function char(i)
   return encoding:sub(i,i)
end

If the list of numbers is in a table, then you may use

function decode(t)
   for i=1,#t do t[i]=char(t[i]) end
   return table.concat(t)
end

You can also save the decoding in a table:

char = {}
for i=1,#encoding do char[i]=encoding:sub(i,i) end

and use char[t[i]] in decode.

Upvotes: 0

Related Questions