Simple Lua Preprocessor

lua-users home
wiki

Simple though this is, it is surprisingly powerful. A slightly more complex version, with a couple of extra features, can be found at the SlightlyLessSimpleLuaPreprocessor.

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

Lines starting with # are executed as Lua. Other lines are sent through as is, except that $(...) appearing anywhere in them is executed. (No parsing is done, so you have to be careful with your $('s)

Sample input:

#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

Sample output:

> 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


RecentChanges · preferences
edit · history
Last edited July 3, 2013 8:02 pm GMT (diff)