Drogobo
Drogobo

Reputation: 13

How do I translate substrings in Lua?

I want to make a translator that translates R U R' U' into r^ u< rv u>. This is very difficult because R' has R in it. So when I try to use this, it spits a result back to me like

put in your algorithm: R U R' U'
r^ u< r^' u<'

Not a very human way of doing it. I think this is because R is a substring of R', but this is what I have been told. I am using this translation thingy from a package called luastring. The dev of luastring won't help me, and this question is too advanced for everyone on the discord server. This is what I have tried so far.

io.write("put in your algorithm: ")
local alg = io.read()

function split(str, pat)
    local t = {}
    local fpat = "(.-)" .. pat
    local last_end = 1
    local s, e, cap = str:find(fpat, 1)
    while s do
        if s ~= 1 or cap ~= "" then table.insert(t, cap) end
        last_end = e + 1
        s, e, cap = str:find(fpat, last_end)
    end
    if last_end <= #str then
        cap = str:sub(last_end)
         table.insert(t, cap)
    end
    return t
end

-- table stuff so we can see
local moves = {"R", "U", "L", "F", "D", "B", "M", "E", "S", "R'", "U'", "L'", "F'", "D'", "B'", "M'", "E'", "S'"}
local neomoves = {"r^", "u<", "lv", "f>", "d>", "b<", "mv", "e>", "s>", "rv", "u>", "l^", "f<", "d<", "b>", "m^", "e<", "s<"}
local string = require("luastring")

local translation_table = {
    ["R'"] = "rv", ["U'"] = "u<", ["L'"] = "lv", ["F'"] = "f>", ["D'"] = "d>", ["B'"] = "b<", ["M'"] = "mv", ["E'"] = "e>", ["S'"] = "s>", ["R"] = "r^", ["U"] = "u<", ["L"] = "lv", ["F"] = "f>", ["D"] = "d>", ["B"] = "b<", ["M"] = "mv", ["E"] = "e>", ["S"] = "s>"
}

-- translate the moves to neomoves
local translated = string.translate(alg, translation_table)
print(translated)

What on earth do I have to do to let Lua know what it is supposed to do?

Upvotes: 0

Views: 1763

Answers (1)

Piglet
Piglet

Reputation: 28950

As your translated string is lower case and the source string is upper case you can simply translate R' befor you translate R.

You only need to split your translation_table into two.

Also you can simply use Lua's standard string.gsub for this. I don't see why you would use luastring here.

Simplified example:

local str = "R' R R' R'"
local t_a = {["R'"] = "rv"}
local t_b = {["R"] = "r^"}
print((str:gsub("%S+", t_a):gsub("%S+", t_b)))

Upvotes: 2

Related Questions