This repository has been archived by the owner on Sep 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathTLua Engine.lua
106 lines (88 loc) · 2.66 KB
/
TLua Engine.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
TLua = {
content = nil,
data = nil,
exportedData = nil,
}
function TLua.checkContent()
if string.sub(TLua.content, -5) == '.tlua' then
TLua.content = TLua.getFileContent(TLua.content)
end
end
function TLua.getFileContent(filename)
local handler = assert(io.open(filename, 'r'))
local content = handler:read('*all')
handler:close()
-- Trim trailing newline
if content:sub(-1) == '\n' then
content = content:sub(1, -2)
end
return content
end
function TLua.render(content, data)
TLua.content = content
TLua.data = data or {}
TLua.checkContent()
TLua.exportData()
TLua.replaceCode()
TLua.replaceVars()
TLua.replaceFiles()
return TLua.content
end
function TLua.replaceVars()
for key, value in pairs(TLua.data) do
local realValue = ''
if type(value) == 'number' or type(value) == 'string' or type(value) == 'boolean' then
realValue = value
end
TLua.content = TLua.content:gsub('{{%s-' .. key .. '%s-}}', TLua.escapePattern(realValue))
end
end
function TLua.replaceCode()
for placeholder, code in TLua.content:gmatch('({{{(.-)}}})') do
TLua.content = TLua.content:gsub(TLua.escapePattern(placeholder), TLua.escapePattern(TLua.runCode(code)))
end
end
function TLua.replaceFiles()
for placeholder, filename in TLua.content:gmatch('(@include%((.-)%))') do
TLua.content = TLua.content:gsub(TLua.escapePattern(placeholder), TLua.escapePattern(TLua.getFileContent(filename)))
end
end
function TLua.runCode(code)
code = TLua.exportedData .. '\n' .. 'return ' .. code
local func = loadstring(code)
return func()
end
function TLua.exportData()
TLua.exportedData = ''
if next(TLua.data) ~= nil then
local keys, values = {}, {}
for key, value in pairs(TLua.data) do
table.insert(keys, key)
if (type(value) == 'number') then
table.insert(values, tostring(value))
elseif (type(value) == 'string') then
table.insert(values, string.format('%q', value))
end
end
TLua.exportedData = 'local ' .. table.concat(keys, ', ') .. ' = ' .. table.concat(values, ', ')
end
end
-- Taken from https://github.com/lua-nucleo/lua-nucleo
function TLua.escapePattern(content)
local matches = {
["^"] = "%^";
["$"] = "%$";
["("] = "%(";
[")"] = "%)";
["%"] = "%%";
["."] = "%.";
["["] = "%[";
["]"] = "%]";
["*"] = "%*";
["+"] = "%+";
["-"] = "%-";
["?"] = "%?";
["\0"] = "%z";
}
return (content:gsub(".", matches))
end