Lua: 返回没有相邻重复的彩虹文本

我对下面的函数为什么不能产生我需要的结果感到有些困惑。第一个函数可以产生结果,但不是我预期的方式。第二个函数可以产生结果,但不是第一个函数的方式。

我试图返回一个带有随机颜色代码注入的字符串,以产生文本的“彩虹”效果。以前,我能够使用xterm做到这一点,所以我想修改原来的函数以适应我当前的需求。下面是我尝试过的函数及其结果。

function rbow(text)
    local colorTable = {"@w", "@b", "@r", "@g", "@y", "@c", "@m", "@W", "@B", "@R", "@G", "@Y", "@C", "@M", "@D"}

    local rcolor, sbyte, lastColor, rtext = 0, 1, 0, ""

    for i = 1, #text do
        local tempTable = {}
        for _,v in ipairs(colorTable) do
            table.insert(tempTable, v)
        end

        if i > 1 then
            table.remove(tempTable, rcolor)
        end

        math.randomseed(os.time() * string.byte(rcolor) * sbyte)
        sbyte = string.byte(i)
        rcolor = math.random(1, #tempTable)
        rtext = rtext .. tempTable[rcolor] .. text:sub(i,i)
    end

    return rtext
end

function rbow2(text)
    local colorTable = {"@w", "@b", "@r", "@g", "@y", "@c", "@m", "@W", "@B", "@R", "@G", "@Y", "@C", "@M", "@D"}
    local rcolor, lastColor, sbyte, rtext = 0, 0, 1, ""

    for i = 1, #text do
        math.randomseed(os.time() * string.byte(rcolor) * sbyte)
        sbyte = string.byte(i)
        rcolor = math.random(1, #colorTable)

        local colorCheck = function()
            if rcolor ~= lastColor then
                rtext = rtext .. tempTable[rcolor] .. text:sub(i,i)
            else
                rcolor = math.random(1, #colorTable)
                colorCheck()
            end
        end
    end

    return rtext
end

print(rbow("这是一个长的字符串,用来查看是否有任何相邻字母重复的颜色。"))

> @bT@Gh@Gi@ys@Y @gi@Cs@D @ya@C @wl@bo@bn@bg@b @bs@bt@br@bi@bn@Gg@G @Gt@Go@G @Gs@Ge@Ge@G @Gi@yf@B @ct@Mh@ye@Br@ce@M @ya@Br@Be@B @Ba@Bn@By@B @Br@Be@Bp@Be@Ga@gt@Ye@gd@Y @gc@Yo@gl@Yo@gr@Cs@b @co@gf@C @bl@ce@gt@Ct@be@Rr@Ys@D @Da@Dd@Dj@Da@Dc@De@Dn@yt@G @yt@Go@y @Ge@ya@Gc@yh@G @yo@Ct@yh@Ce@yr@C。

 print(rbow2("这是一个长的字符串,用来查看是否有任何相邻字母重复的颜色。"))

> 0

在第一个例子中,相邻字母用相同的颜色代码表示,例如:

@bo@bn@bg@b @bs@bt@br@bi@bn -- 所有的 @b
@G @Gt@Go@G @Gs@Ge@Ge@G @Gi -- 所有的 @G

等等。奇怪的因素是,相同的模式(具有不同的颜色代码)几乎在后续返回中重复。它不能完全匹配,但在三次打印中,“to see”和“adjacent”在单词中带有相同的颜色代码。

我不确定该怎么处理这个问题。我不想让它在相邻的字母中重复颜色,我认为第一个函数会解决这个问题,从tempTable中删除最近使用的颜色代码。我错过了什么?

点赞