einsteinK

Lua - String/Comment Parser

Jun 29th, 2016
420
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.99 KB | None | 0 0
  1.  
  2. local rules = {
  3.     {"%-%-%[(=*)%[.-%]%1%]","COMMENT"};
  4.     {"%-%-.-\n","COMMENT"};
  5.     {"['\"]","START"};
  6.     {"%[(=*)%[.-%]%1%]","LONGSTRING"};
  7.     {"[^%[-'\"]+","OTHER"};
  8. }
  9.  
  10. local function parse(source)
  11.     local result,i = {},1
  12.     local function parser()
  13.         if i == #source + 1 then return end
  14.         for k,v in pairs(rules) do
  15.             local a,b = source:find(v[1],i)
  16.             if a == i then i = b+1
  17.                 return v[2],source:sub(a,b),a
  18.             end
  19.         end error("No rule found at pos "..i,0)
  20.     end
  21.     for typ,part,start in parser do
  22.         --print(typ,part,start)
  23.         if typ == "START" then local st = start+1
  24.             local a,b = source:find("\\*"..part,st)
  25.             while a do st = b + 1
  26.                 if (b-a)%2==0 then a=nil break end
  27.                 a,b = source:find("\\*"..part,st)
  28.             end
  29.             if b and not a then i = b+1
  30.                 local str = source:sub(start,b)
  31.                 -- print"hi" will make 'str' be "hi" (including quotes)
  32.                 table.insert(result,"(sandboxstring"..str..")")
  33.             else
  34.                 error("Couldn't find closing quote thingy starting at pos "..start,0)
  35.             end
  36.         elseif typ == "LONGSTRING" then
  37.             table.insert(result,"(sandboxstring"..part..")")
  38.         elseif typ == "COMMENT" then
  39.             -- ignore? idk. Could parse javadocs or whatever for fun
  40.         else
  41.             table.insert(result,part)
  42.         end
  43.     end
  44.     return table.concat(result)
  45. end
  46.  
  47. local code = parse[==========[
  48. print"pls"
  49. print'hi'
  50. -- comment that'll get ignored
  51. print[==[
  52.     long
  53.     bananas
  54. ]==]
  55. --[[
  56.     This one gets ignored too, yeuy!
  57. --]]
  58. print[[not-so-long bananas with " and ' quotes and [=[this thing]=] ]]
  59. print("Ah putting ' in here works fine")
  60. print("Putting \" with backslash works fine too")
  61. ]==========]
  62.  
  63. print(code)
  64. assert(loadstring(code))
  65.  
  66.  
  67.  
  68.  
  69.  
  70.  
  71. --[[ START OF RESULT
  72. print(sandboxstring"pls")
  73. print(sandboxstring'hi')
  74. print(sandboxstring[==[
  75.     long
  76.     bananas
  77. ]==])
  78.  
  79. print(sandboxstring[[not-so-long bananas with " and ' quotes and [=[this thing]=] ]])
  80. print((sandboxstring"Ah putting ' in here works fine"))
  81. print((sandboxstring"Putting \" with backslash works fine too"))
  82. --]] END OF RESULT
Add Comment
Please, Sign In to add comment