Lua:针对特定场景的一小段代码

我正在用Lua编写一个(可怜的)加密脚本,为此,我需要编写一个循环,这个循环将为字符串中的每个数字返回一个值,例如:

输入:15, 18, 1, 20, 15, 18, 15, 5, 21, 1, 18, 15, 21, 16, 1, 4, 15, 18, 5, 9, 4, 5, 18, 15, 13, 1

然后我希望它将每个数字返回给一个函数,该函数将对它们进行某些数学计算,然后返回对应的字母(15将变为“o”,18将变为“r”等等)。

详细解释一下,我需要一个可以插入到功能中的代码片段,它将:

  1. 将字符串中的每个数字返回给一个函数。

  2. 在此之后,函数需要将数字转换为字母(如上所述)。

  3. 然后,新的函数需要将结果字母插入到新字符串中。

以下是它应该如何运行的简要示例。

输入:8, 5, 12, 12, 15
结果:26, 7, 15, 15, 12(由于函数内部的隐藏数学而造成这些数字不是常量。)

输入:26, 7, 15, 15, 12
结果:z,g,o,o,l

输入:z,g,o,o,l
结果:“zgool”

我认为此项目的源代码对此次机会并不重要,我只会将此代码实现到脚本的函数中。请有人(谁明白我的意思)来帮助我吗?

点赞
用户6834680
用户6834680
```lua
local function my_poor_cryptography(s)
   local codes = {}
   -- string to numbers
   for c in s:gmatch"%a" do
      table.insert(codes, c:byte() - (c:find"%l" and 96 or 64))
   end
   -- math here (https://en.wikipedia.org/wiki/ROT13)
   for j = 1, #codes do
      codes[j] = (codes[j] + 12) % 26 + 1
   end
   -- numbers to string
   s = s:gsub("%a",
      function(c)
         return c.char(table.remove(codes, 1) + (c:find"%l" and 96 or 64))
      end)
   return s
end

使用方法:

local str = "Hello, World!"
str = my_poor_cryptography(str)
print(str)     --> Uryyb, Jbeyq!
str = my_poor_cryptography(str)
print(str)     --> Hello, World!

```

2017-12-07 14:54:03