Skip to content

Instantly share code, notes, and snippets.

@CandyMi
Last active July 16, 2024 08:50
Show Gist options
  • Save CandyMi/0238ca1f474092dacd32f04918f5847d to your computer and use it in GitHub Desktop.
Save CandyMi/0238ca1f474092dacd32f04918f5847d to your computer and use it in GitHub Desktop.
ascii的编码和解码

ascii的编码和解码

测试代码

local ascii = require "ascii"
print(ascii.encode('我123321sdacsdavsd'))
print(ascii.decode('我123321sdacsdavsd'))

测试结果

我123321sdacsdavsd
我123321sdacsdavsd
local toint = math.tointeger
local gsub = string.gsub
local fmt = string.format
local u8_char = utf8.char
local u8_codepoint = utf8.codepoint
local u8_charpattern = utf8.charpattern
local function enc_cb(s)
return fmt('&#%d;', u8_codepoint(s))
end
local function dec_cb(s)
local n = toint(s)
return n and u8_char(n) or ('&#' .. s .. ';')
end
local ascii = { }
---comment 将文本转换为`ascii`编码
---@param text string @编码文本
function ascii.encode(text)
local v = gsub(text, u8_charpattern, enc_cb)
return v
end
---comment 将文本内的`ascii`解码
---@param text string @解码文本
function ascii.decode(text)
local v = gsub(text, "&#([%d]+);", dec_cb)
return v
end
return ascii
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment