Repository navigation
Expand file tree
/
Copy pathlua-runtime.js
More file actions
303 lines (295 loc) · 14.5 KB
/
Copy pathlua-runtime.js
File metadata and controls
303 lines (295 loc) · 14.5 KB
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
(function (root) {
var PRELUDE = [
"local emit = __emit",
"__emit = nil",
"local realDebug = debug",
"local STOP = {}",
"local scheduled, timers = {}, {}",
"local stopped = false",
"local function fmt(v, depth)",
" depth = depth or 0",
" local t = type(v)",
" if t == 'string' then return string.format('%q', v):gsub('\\\\\\n', '\\\\n') end",
" if t == 'table' then",
" local mt = getmetatable(v)",
" if mt and mt.__mock then return mt.__mock end",
" if depth > 1 then return '{...}' end",
" local parts, n, len = {}, 0, #v",
" for i = 1, len do",
" n = n + 1",
" if n > 8 then parts[#parts + 1] = '...' break end",
" parts[#parts + 1] = fmt(v[i], depth + 1)",
" end",
" local keys = {}",
" for k in pairs(v) do if not (math.type(k) == 'integer' and k >= 1 and k <= len) then keys[#keys + 1] = k end end",
" table.sort(keys, function(a, b) return tostring(a) < tostring(b) end)",
" for _, k in ipairs(keys) do",
" n = n + 1",
" if n > 8 then parts[#parts + 1] = '...' break end",
" parts[#parts + 1] = tostring(k) .. ' = ' .. fmt(v[k], depth + 1)",
" end",
" return '{ ' .. table.concat(parts, ', ') .. ' }'",
" end",
" if t == 'function' then return 'function' end",
" if t == 'number' and math.type(v) == 'float' then return (string.format('%.6g', v)) end",
" return tostring(v)",
"end",
"local function args(...)",
" local n, p = select('#', ...), {}",
" for i = 1, n do p[i] = fmt((select(i, ...))) end",
" return table.concat(p, ', ')",
"end",
"local function text(...)",
" local n, p = select('#', ...), {}",
" for i = 1, n do local v = select(i, ...) p[i] = type(v) == 'string' and v or fmt(v) end",
" return table.concat(p, ' ')",
"end",
"local messages = {",
" ['debug.print'] = 'print', ['debug.info'] = 'info', ['debug.warn'] = 'warn', ['debug.error'] = 'error',",
" debugPrint = 'print', luaTrace = 'print', debugInfo = 'info', debugWarn = 'warn', debugError = 'error', print = 'print'",
"}",
"local special = {}",
"special['song.atBeat'] = function(beat, fn) scheduled[#scheduled + 1] = { beat = tonumber(beat) or 0, fn = fn } end",
"special['timer.after'] = function(sec, fn) timers[#timers + 1] = { kind = 'after', fn = fn } end",
"special['runTimer'] = function(tag, sec, loops) timers[#timers + 1] = { kind = 'timer', tag = tag, loops = loops or 1 } end",
"special['save.get'] = function(k, d) return d end",
"special['getDataFromSave'] = function(f, k, d) return d end",
"special['LuaSlice.versionAtLeast'] = function() return true end",
"special['requiresLuaSlice'] = function() return true end",
"special['script.stop'] = function() stopped = true error(STOP, 0) end",
"special['stopCurrentLuaScript'] = special['script.stop']",
"special['openCustomSubstate'] = function(name) timers[#timers + 1] = { kind = 'substate', name = name } end",
"special['getHealth'] = function() return health end",
"special['addHealth'] = function(v) health = math.max(0, math.min(2, (health or 1) + (tonumber(v) or 0))) end",
"special['setHealth'] = function(v) health = tonumber(v) or health end",
"special['addScore'] = function(v) score = (score or 0) + (tonumber(v) or 0) end",
"special['getRandomInt'] = function(a, b) return math.random(tonumber(a) or 0, tonumber(b) or 1) end",
"special['getRandomFloat'] = function(a, b) a = tonumber(a) or 0 b = tonumber(b) or 1 return a + math.random() * (b - a) end",
"special['randomInt'] = special['getRandomInt']",
"special['randomFloat'] = special['getRandomFloat']",
"local function default(path, ...)",
" local last = path:match('([%w_]+)$') or path",
" if last:match('^doTween') or last == 'startTween' then local tag = ... timers[#timers + 1] = { kind = 'tween', tag = tag, target = select(2, ...) } return nil end",
" if last:match('JustPressed$') or last:match('JustReleased$') or last:match('Pressed$') or last:match('^key') then return false end",
" if last == 'exists' or last == 'make' or last:match('^is') or last:match('Exists$') then return true end",
" if last:match('^get') or last == 'mouseX' or last == 'mouseY' then return 0 end",
" return nil",
"end",
"local calls = 0",
"local function callmock(path, ...)",
" calls = calls + 1",
" local level = messages[path]",
" if level then emit(level, text(...)) return end",
" emit('call', path .. '(' .. args(...) .. ')')",
" local fn = special[path]",
" if fn then return fn(...) end",
" return default(path, ...)",
"end",
"local function mock(path)",
" return setmetatable({}, {",
" __mock = path,",
" __index = function(t, k)",
" local m = mock(path .. '.' .. tostring(k))",
" rawset(t, k, m)",
" return m",
" end,",
" __call = function(self, ...) return callmock(path, ...) end,",
" __tostring = function() return path end,",
" __concat = function(a, b) return tostring(a) .. tostring(b) end",
" })",
"end",
"print = function(...) return callmock('print', ...) end",
"debug = mock('debug')",
"rawset(debug, 'traceback', realDebug.traceback)",
"rawset(debug, 'getinfo', realDebug.getinfo)",
"LuaSlice = mock('LuaSlice')",
"rawset(LuaSlice, 'version', '0.1.0')",
"setmetatable(_G, { __index = function(t, k)",
" if type(k) ~= 'string' or k:match('^on%u') or k:match('NoteHit$') or k == 'noteMiss' or k == 'noteMissPress' then return nil end",
" local m = mock(k)",
" rawset(t, k, m)",
" return m",
"end })",
"local GLOBALS = {",
" luaslice = { luaSupportVersion = '0.1.0', luaScriptCount = 1, luaGlobalScriptCount = 0, luaIsolatedScriptCount = 0,",
" songName = 'Tutorial', songId = 'tutorial', difficultyName = 'normal', variationName = 'default', stageId = 'mainStage',",
" curBeat = 0, curStep = 0, songPosition = 0, health = 1, score = 0, combo = 0, botPlay = false, practice = false },",
" psych = { version = '1.0.4', vSliceVersion = '0.7.0', scriptName = 'script.luap', modFolder = 'my-mod',",
" curBeat = 0, curStep = 0, curDecBeat = 0, curDecStep = 0, curSection = 0, bpm = 120, curBpm = 120, crochet = 500, stepCrochet = 125,",
" songPosition = 0, songName = 'Tutorial', songPath = 'tutorial', songLength = 60000, curStage = 'mainStage',",
" screenWidth = 1280, screenHeight = 720, downscroll = false, scrollSpeed = 1, score = 0, health = 1, difficultyName = 'normal',",
" inGameOver = false, mustHitSection = false,",
" Function_Continue = '##PSYCHLUA_FUNCTIONCONTINUE', Function_Stop = '##PSYCHLUA_FUNCTIONSTOP',",
" Function_StopLua = '##PSYCHLUA_FUNCTIONSTOPLUA', Function_StopAll = '##PSYCHLUA_FUNCTIONSTOPALL' }",
"}",
"function __setup(api)",
" for k, v in pairs(GLOBALS[api] or {}) do rawset(_G, k, v) end",
"end",
"local function hook(name, ...)",
" if stopped then return false end",
" local f = rawget(_G, name)",
" if type(f) ~= 'function' then return true end",
" emit('hook', name .. '(' .. args(...) .. ')')",
" local ok, err = pcall(f, ...)",
" if not ok then",
" if err == STOP then emit('warn', 'script.stop() was called, the script stopped') return false end",
" error(err, 0)",
" end",
" return true",
"end",
"local function flush(api)",
" local guard = 0",
" while #timers > 0 and guard < 200 do",
" guard = guard + 1",
" local t = table.remove(timers, 1)",
" if t.kind == 'after' and type(t.fn) == 'function' then",
" emit('hook', 'timer callback')",
" local ok, err = pcall(t.fn)",
" if not ok then if err == STOP then return false end error(err, 0) end",
" elseif t.kind == 'timer' then",
" if not hook('onTimerCompleted', t.tag, t.loops, 0) then return false end",
" elseif t.kind == 'tween' then",
" if not hook('onTweenCompleted', t.tag, t.target) then return false end",
" elseif t.kind == 'substate' then",
" if not hook('onCustomSubstateCreate', t.name) then return false end",
" if not hook('onCustomSubstateUpdate', t.name, 1 / 60) then return false end",
" end",
" end",
" return true",
"end",
"local function step(name, ...)",
" if not hook(name, ...) then return false end",
" return flush()",
"end",
"function __simulate(api, beats, noteKind, noteBeat, eventName, eventBeat, v1, v2)",
" local ps = api == 'psych'",
" local seq = ps and { 'onCreate', 'onCreatePost', 'onStartCountdown', 'onSongStart' } or { 'onCreate', 'onCreatePost', 'onSongLoaded', 'onCountdownStart', 'onCountdownEnd', 'onSongStart' }",
" for _, h in ipairs(seq) do if not step(h) then return calls end end",
" for b = 1, beats do",
" for s = 1, 4 do",
" curStep = (b - 1) * 4 + s",
" if ps then curDecStep = curStep end",
" if ps then if not step('onStepHit') then return calls end else if not step('onStepHit', curStep) then return calls end end",
" end",
" curBeat = b",
" songPosition = b * 500",
" if ps then curDecBeat = b curSection = math.floor(b / 4) end",
" for _, s in ipairs(scheduled) do",
" if s.beat == b and type(s.fn) == 'function' then",
" emit('hook', 'song.atBeat(' .. b .. ') callback')",
" local ok, err = pcall(s.fn)",
" if not ok then if err == STOP then return calls end error(err, 0) end",
" end",
" end",
" if not flush() then return calls end",
" if ps then if not step('onBeatHit') then return calls end else if not step('onBeatHit', b) then return calls end end",
" if ps and b % 4 == 0 and not step('onSectionHit') then return calls end",
" if not ps and b % 4 == 0 and not step('onSectionHit', b // 4) then return calls end",
" if not step('onUpdate', 1 / 60) then return calls end",
" if ps and not step('onUpdatePost', 1 / 60) then return calls end",
" if noteKind and b == noteBeat then",
" if ps then",
" if not step('goodNoteHit', 0, 2, noteKind, false) then return calls end",
" if not step('opponentNoteHit', 1, 1, noteKind, false) then return calls end",
" if not step('noteMiss', 2, 3, noteKind, false) then return calls end",
" else",
" local ev = { note = { kind = noteKind, direction = 2, mustHit = true }, healthChange = 0.02, judgement = 'sick' }",
" if not step('onNoteHit', ev) then return calls end",
" if not step('onNoteMiss', { note = { kind = noteKind, direction = 3, mustHit = true }, healthChange = -0.04 }) then return calls end",
" end",
" end",
" if eventName and b == eventBeat then",
" if ps then",
" if not step('onEvent', eventName, v1, v2, songPosition) then return calls end",
" else",
" if not step('onSongEvent', { name = eventName, value = { v1, v2 }, time = songPosition }) then return calls end",
" end",
" end",
" end",
" if ps then step('onEndSong') else step('onSongEnd') end",
" step('onDestroy')",
" emit('info', 'Health ' .. string.format('%.2f', health or 1) .. ', score ' .. tostring(score or 0))",
" return calls",
"end"
].join('\n');
function create(F) {
var lua = F.lua, lauxlib = F.lauxlib, lualib = F.lualib, S = F.to_luastring;
function check(code) {
var L = lauxlib.luaL_newstate();
var src = S(code);
var st = lauxlib.luaL_loadbuffer(L, src, src.length, S('=script'));
var msg = st === 0 ? null : lua.lua_tojsstring(L, -1);
lua.lua_close(L);
return msg ? parseError(msg) : null;
}
function parseError(msg) {
var m = /script:(\d+):\s*(.*)$/.exec(msg);
return { line: m ? +m[1] : 0, message: m ? m[2] : msg, raw: msg };
}
function run(code, opts, out) {
opts = opts || {};
var started = Date.now();
var lines = 0, limit = opts.maxLines || 3000, cut = false;
var L = lauxlib.luaL_newstate();
lualib.luaL_openlibs(L);
lua.lua_pushcfunction(L, function (L) {
var kind = lua.lua_tojsstring(L, 1), text = lua.lua_tojsstring(L, 2);
if (lines < limit) out(kind, text);
else if (!cut) { cut = true; out('warn', 'Output truncated after ' + limit + ' lines'); }
lines++;
return 0;
});
lua.lua_setglobal(L, S('__emit'));
var budget = opts.budget || 400;
var ticks = 0;
lua.lua_sethook(L, function (L) {
if (++ticks > budget) lauxlib.luaL_error(L, S('script ran too long, is there an infinite loop?'));
}, lua.LUA_MASKCOUNT, 100000);
function exec(src, name) {
var buf = S(src);
var st = lauxlib.luaL_loadbuffer(L, buf, buf.length, S(name));
if (st === 0) st = lua.lua_pcall(L, 0, 0, 0);
if (st !== 0) {
var msg = lua.lua_tojsstring(L, -1);
lua.lua_pop(L, 1);
return msg || 'unknown error';
}
return null;
}
var result = { ok: true, error: null, calls: 0, ms: 0 };
var err = exec(PRELUDE, '=prelude');
if (!err) {
lua.lua_getglobal(L, S('__setup'));
lua.lua_pushstring(L, S(opts.api || 'luaslice'));
lua.lua_pcall(L, 1, 0, 0);
err = exec(code, '=script');
}
if (!err) {
lua.lua_getglobal(L, S('__simulate'));
lua.lua_pushstring(L, S(opts.api || 'luaslice'));
lua.lua_pushinteger(L, Math.max(0, Math.min(1024, opts.beats | 0)));
if (opts.noteKind) lua.lua_pushstring(L, S(opts.noteKind)); else lua.lua_pushnil(L);
lua.lua_pushinteger(L, opts.noteBeat | 0);
if (opts.eventName) lua.lua_pushstring(L, S(opts.eventName)); else lua.lua_pushnil(L);
lua.lua_pushinteger(L, opts.eventBeat | 0);
lua.lua_pushstring(L, S(opts.value1 || ''));
lua.lua_pushstring(L, S(opts.value2 || ''));
var st = lua.lua_pcall(L, 8, 1, 0);
if (st !== 0) { err = lua.lua_tojsstring(L, -1) || 'unknown error'; }
else result.calls = lua.lua_tointeger(L, -1);
}
lua.lua_close(L);
if (err) {
result.ok = false;
result.error = parseError(err);
out('error', err);
}
result.ms = Date.now() - started;
return result;
}
return { run: run, check: check };
}
var api = { create: create };
if (typeof module !== 'undefined' && module.exports) module.exports = api;
else root.LuaSliceRuntime = api;
})(this);