Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require "re" -- no shit sherlock
- -- this is the table that holds all the \substitutions
- -- it could easily be hardcoded into descape() but why bother
- descapetable = {
- ['\\\\'] = '\\',
- ['\\"'] = '"', ['\\/'] = '/',
- ['\\t'] = '\9', ['\\n'] = '\10',
- ['\\f'] = '\12', ['\\r'] = '\13',
- }
- -- this function does the unescaping in strings
- -- you could do this within the PEG using substitution captures
- -- (at least, for everything besides the unicode)
- -- but i just said fuck it and moved on with the bot
- function descape (str)
- local tab = {}
- -- unicode support
- -- str = str:gsub('\\u(%x+)', function (num) end)
- -- other escapes
- for c in str:gmatch'\\?.' do
- if c == '\\b' then
- tab[#tab] = nil
- else
- tab[1+#tab] = descapetable[c] or c
- end
- end
- return table.concat(tab)
- end
- -- json:match(str) decodes str from json into a table
- -- note: both {objects} and [arrays] are translated to lua tables
- json = re.compile([[
- value <- %s* ( object / array / string / {number} / ('true' / 'false') -> bool / 'null' -> null ) %s*
- key <- %s* string %s*
- object <- '{' ( key ':' value ','? )* -> {} -> object '}'
- array <- '[' ( value ','? )* -> {} ']'
- string <- '"' { ( [^"\] / {escape} )* } -> unesc '"'
- escape <- '\' ( ["\/bfnrt] / 'u' %x^-4 )
- number <- '-'? ( '0' / [1-9] %d* ) ( '.' %d+ )? ( [eE] [+-]? %d+ )?
- ]], {
- bool = function (s) return s == 'true' end,
- null = function () return nil end,
- unesc = descape,
- object = function (tab)
- -- this is probably a little hackish
- for i=1,#tab,2 do
- tab[tab[i]], tab[i], tab[i+1] = tab[i+1]
- end
- return tab
- end,
- })
Advertisement
Add Comment
Please, Sign In to add comment