Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a number to its alphabetical counterpart in lua

Tags:

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?

like image 977
Alexwall Avatar asked Dec 15 '22 09:12

Alexwall


2 Answers

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
like image 131
Paul Kulchenko Avatar answered Dec 28 '22 23:12

Paul Kulchenko


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
like image 41
Veer Singh Avatar answered Dec 28 '22 23:12

Veer Singh