示例工程 11-formatting-and-bytes

11-formatting-and-bytes/02-q-roundtrip/main.lua

lua · 0.5 KB

-- @runtimes lua54 luajit
--- 演示:%q 的转义与往返。
local M = {}
 
--- @return table { quoted = string, roundtrip = boolean }
function M.run(log)
	log = log or print
	local source = 'line\nquote"tab\t'
	local quoted = string.format("%q", source)
	local loaded = assert(load("return " .. quoted))()
	log(("quoted=%s"):format(quoted))
	log(("roundtrip=%s"):format(tostring(loaded == source)))
	return { quoted = quoted, roundtrip = loaded == source }
end
 
if not ... then
	M.run()
end
return M