For my game, I want to create a morse code translator, where it will take in morse code and output normal text, I have a table of morse code to text values so all I have to do is write a function that translates it. Since each character in morse code requires a space, for example,
.... .. --[[ hi because h = ...., i = .. ]]
actual spaces are 3 spaces long.
.... . .-.. .-.. --- .-- --- .-. .-.. -.. this is "hello world" notice how between hello and world there is 3 spaces.
That is the exact problem I am facing here, each time I put this in the function, I expect it to return “hello world”, but it actually returns helloworld. I try to split each morse code group into a table. Then I compare them to the dictonary.
local MORSE_CODE = {
[".-"] = "A",
["-..."] = "B",
["-.-."] = "C",
["-.."] = "D",
["."] = "E",
["..-."] = "F",
["--."] = "G",
["...."] = "H",
[".."] = "I",
[".---"] = "J",
["-.-"] = "K",
[".-.."] = "L",
["--"] = "M",
["-."] = "N",
["---"] = "O",
[".--."] = "P",
["--.-"] = "Q",
[".-."] = "R",
["..."] = "S",
["-"] = "T",
["..-"] = "U",
["...-"] = "V",
[".--"] = "W",
["-..-"] = "X",
["-.--"] = "Y",
["--.."] = "Z",
["-----"] = "0",
[".----"] = "1",
["..---"] = "2",
["...--"] = "3",
["....-"] = "4",
["....."] = "5",
["-...."] = "6",
["--..."] = "7",
["---.."] = "8",
["----."] = "9",
[".-.-.-"] = ".",
["--..--"] = ",",
["..--.."] = "?",
[".----."] = "'",
["-.-.--"] = "!",
["-..-."] = "/",
["-.--."] = "(",
["-.--.-"] = ")",
[".-..."] = "&",
["---..."] = "=>",
["-.-.-."] = ";",
["-...-"] = "=",
[".-.-."] = "+",
["-....-"] = "-",
["..--.-"] = "_",
[".-..-."] = "\"",
["...-..-"] = "$",
[".--.-."] = "@",
["...---..."] = "SOS"
}
local function split(inputstr, sep)
if sep == nil then
sep = "%S+"
end
local t = {}
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
table.insert(t, str)
end
return t
end
local function decode_morse_code(morse_code)
local splitStrings = split(morse_code, " ")
local newTable = {}
for i, v in pairs(splitStrings) do
table.insert(newTable, MORSE_CODE[v])
end
local hi = ftostring(newTable)
return hi
end
print(decode_morse_code(".... . -.-- .--- ..- -.. .")) --it should print HEY JUDE, but it prints HEYJUDE
Everything else I got working, ftostring(newTable)
is a helper function for formatting the table, but the fact is, when the parser goes through the 3 spaces, it ignores them and parses them out. I don’t want that, because then it will result in morse code with no spaces.