简单 Lua 预处理器 |
|
function prep(file) local chunk = {n=0} for line in file:lines() do if string.find(line, "^#") then table.insert(chunk, string.sub(line, 2) .. "\n") else local last = 1 for text, expr, index in string.gmatch(line, "(.-)$(%b())()") do last = index if text ~= "" then table.insert(chunk, string.format('io.write %q ', text)) end table.insert(chunk, string.format('io.write%s ', expr)) end table.insert(chunk, string.format('io.write %q\n', string.sub(line, last).."\n")) end end return loadstring(table.concat(chunk))() end
以 # 开头的行将作为 Lua 代码执行。其他行将原样发送,除了它们中出现的 $(...) 将被执行。(没有进行解析,所以你必须小心你的 $('s)
示例输入
#if DEBUG then function log(fmt, ...) print(string.format(fmt, unpack(arg))) end #else function log() end #end #for i = 0, 10 do var$(i) = $(math.sin(math.pi * i / 10)) #end
示例输出
> prep(assert(io.open"sample.luap")) function log() end var0 = 0 var1 = 0.30901699437495 var2 = 0.58778525229247 var3 = 0.80901699437495 var4 = 0.95105651629515 var5 = 1 var6 = 0.95105651629515 var7 = 0.80901699437495 var8 = 0.58778525229247 var9 = 0.30901699437495 var10 = 1.2246467991474e-16 > DEBUG = true > prep(assert(io.open"sample.luap")) function log(fmt, ...) print(string.format(fmt, unpack(arg))) end var0 = 0 var1 = 0.30901699437495 var2 = 0.58778525229247 var3 = 0.80901699437495 var4 = 0.95105651629515 var5 = 1 var6 = 0.95105651629515 var7 = 0.80901699437495 var8 = 0.58778525229247 var9 = 0.30901699437495 var10 = 1.2246467991474e-16