Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
ltin/ltin.lua
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
48 lines (45 sloc)
1.45 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| local table = require('table') | |
| local ltin = {} | |
| local sandbox = {} | |
| -- Parse ltin code by reusing the lua parser in a sandbox | |
| function ltin.parse(string) | |
| local fn, message = loadstring("return " .. string) | |
| if not fn then error(message) end | |
| setfenv(fn, sandbox) | |
| return fn() | |
| end | |
| -- stringify data to ltin using a pretty-printer | |
| function ltin.stringify(value) | |
| local t = type(value) | |
| if t == "number" or t == "boolean" or t == "nil" then | |
| return tostring(value) | |
| end | |
| if t == "string" then | |
| return '"' .. value:gsub("\\", "\\\\") | |
| :gsub("%z", "\\0"):gsub("\a", "\\a"):gsub("\b", "\\b") | |
| :gsub("\f", "\\f"):gsub("\n", "\\n"):gsub("\r", "\\r") | |
| :gsub("\t", "\\t"):gsub("\v", "\\v"):gsub('"', '\\"') .. '"' | |
| end | |
| if t == 'table' then | |
| local parts = {} | |
| local index = 1 | |
| for key, item in pairs(value) do | |
| local keyString | |
| if key == index then | |
| keyString = "" | |
| elseif type(key) == "string" and key:match("^[_%a][_%w]*$") then | |
| keyString = key .. "=" | |
| else | |
| keyString = "[" .. ltin.stringify(key) .. "]=" | |
| end | |
| parts[index] = keyString .. ltin.stringify(item) | |
| index = index + 1 | |
| end | |
| return "{" .. table.concat(parts, ",") .. "}" | |
| end | |
| return "'" .. tostring(value):gsub("\\", "\\\\") | |
| :gsub("%z", "\\0"):gsub("\a", "\\a"):gsub("\b", "\\b") | |
| :gsub("\f", "\\f"):gsub("\n", "\\n"):gsub("\r", "\\r") | |
| :gsub("\t", "\\t"):gsub("\v", "\\v"):gsub("'", "\\'") .. "'" | |
| end | |
| return ltin |