Lua:'for'循环问题(string.gsub)

时间:2017-12-02 21:29:03

标签: lua

我正在制作一个用于自定义加密字符串的lua脚本,但我找不到一个循环,用于将字母替换为与字母表对应的数字。    它必须返回这样的东西:

  "hello"
> 8, 4, 12, 12, 15 

这将是加密过程的第一部分,但我不能编程这样的循环,任何帮助? (下面的脚本:)

local text = "what"

local key = math.random(100000, 500000) 
local pie = math.pi 
local n = 26

local alpha = { a = 1, b = 2, c = 3, d = 4, e = 5, f = 6 , g = 7, h = 8, i = 9, j = 10, 
k = 11, l = 12, m = 13, n = 14, o = 15, p = 16, q = 17, r = 18, s = 19, t = 20, u = 21, v = 22, w = 23, x = 24, y = 25, z = 26} 


function enumerate(str) 
 return str:gsub("%l", function(c) return c.char(c:byte()-96) end):byte(1,-1) 
end

更新:新问题,如何将数字返回为:

46, 68, 46, 32, 4, 12, 18, 15, 23, 32, 15, 23, 5, 8     

而不是字符串空格

"46 68 46 32 4 12 18 15 23 32 15 23 5 8"    

1 个答案:

答案 0 :(得分:0)

你只需要使用explode + encode(见下文)收集表上的每个字符,然后调用unpack(或table.unpack)来获取元组。

首先爆炸:

function explode(str)
    local ret = {}
    for c in str:gmatch(".") do 
        table.insert(ret, c)
    end
    return ret 
end

编码部分可以这样做:

local BASE_CHAR = ("a"):byte()

function encode(c) 
    return c:byte() - BASE_CHAR + 1
end

把所有东西放在一起:

unpack = unpack or table.unpack -- Handling lua 5.1 or higher

function enumerate(str) -- Keeping the original name
    local exploded = {}
    for i, c in ipairs(explode(str)) do
        exploded[i] = encode(c)
    end
    return unpack(exploded)
end

测试:

print(enumerate("test"))

产生以下结果:

20      5       19      20

注意:

我更喜欢将结果保存在表格中,只在必要时才打开包装。这样你就可以按照你想要的方式操作表格,这比处理元组更方便:

function enumerate(str) -- Keeping the original name
    local exploded = {}
    for i, c in ipairs(explode(str)) do
        exploded[i] = encode(c)
    end
    return exploded
end

print(unpack(enumerate("test")))

如果你想要一个字符串:

print(table.concat(enumerate("test"), ", "))

希望这能解决问题

相关问题