Репозитории / Promptly / public/js/lua-bridge.js

lua-bridge.js

К файлам Скачать / raw
1// Мост Lua ↔ JS для интерактивных презентаций.
2// Использует глобальный fengari (vendor/fengari-web.js).
3// Скрипты выполняются в корутине: доступен sleep(ms), анимации через таблицу anim.
4(function () {
5 const { lua, lauxlib, lualib, to_luastring, to_jsstring } = window.fengari;
6 const T = lua;
7 const luaYield = T.lua_yield || ((Ls, n) => T.lua_yieldk(Ls, n, null, null));
8
9 function readValue(L, idx) {
10 const type = T.lua_type(L, idx);
11 if (type === T.LUA_TBOOLEAN) return !!T.lua_toboolean(L, idx);
12 if (type === T.LUA_TNUMBER) return T.lua_tonumber(L, idx);
13 if (type === T.LUA_TSTRING) {
14 const s = T.lua_tostring(L, idx);
15 return s ? to_jsstring(s) : '';
16 }
17 return null;
18 }
19
20 function tableToJs(L, idx) {
21 const abs = T.lua_absindex(L, idx);
22 const len = T.lua_rawlen(L, abs);
23 if (len > 0) {
24 const arr = [];
25 for (let i = 1; i <= len; i += 1) {
26 T.lua_rawgeti(L, abs, i);
27 arr.push(valueToJs(L, -1));
28 T.lua_pop(L, 1);
29 }
30 return arr;
31 }
32 const obj = {};
33 T.lua_pushnil(L);
34 while (T.lua_next(L, abs) !== 0) {
35 const key = readValue(L, -2);
36 obj[key === null ? '' : String(key)] = valueToJs(L, -1);
37 T.lua_pop(L, 1);
38 }
39 return obj;
40 }
41
42 function valueToJs(L, idx) {
43 const type = T.lua_type(L, idx);
44 if (type === T.LUA_TTABLE) return tableToJs(L, idx);
45 return readValue(L, idx);
46 }
47
48 function pushValue(L, value) {
49 if (typeof value === 'number' && Number.isFinite(value)) T.lua_pushnumber(L, value);
50 else if (typeof value === 'boolean') T.lua_pushboolean(L, value);
51 else if (typeof value === 'string') T.lua_pushstring(L, to_luastring(value));
52 else T.lua_pushnil(L);
53 }
54
55 function jsString(L, idx) {
56 const s = T.lua_tostring(L, idx);
57 return s ? to_jsstring(s) : '';
58 }
59
60 function createRuntime(hooks = {}) {
61 const L = lauxlib.luaL_newstate();
62 lualib.luaL_openlibs(L);
63
64 const noop = () => {};
65 const h = {
66 go: hooks.go || noop,
67 next: hooks.next || noop,
68 prev: hooks.prev || noop,
69 play: hooks.play || noop,
70 stop: hooks.stop || noop,
71 volume: hooks.volume || noop,
72 music: hooks.music || noop,
73 musicPlay: hooks.musicPlay || noop,
74 musicStop: hooks.musicStop || noop,
75 musicVolume: hooks.musicVolume || noop,
76 videoPlay: hooks.videoPlay || noop,
77 videoPause: hooks.videoPause || noop,
78 videoRestart: hooks.videoRestart || noop,
79 videoSeek: hooks.videoSeek || noop,
80 currentSlide: hooks.currentSlide || (() => 1),
81 animate: hooks.animate || noop,
82 animateClear: hooks.animateClear || noop,
83 log: hooks.log || ((msg) => console.log('[lua]', msg)),
84 error: hooks.error || ((msg) => console.error('[lua]', msg)),
85 };
86
87 const setFn = (name, fn) => {
88 T.lua_pushcfunction(L, (state) => {
89 try {
90 return fn(state) || 0;
91 } catch (err) {
92 h.error(String(err && err.message ? err.message : err));
93 return 0;
94 }
95 });
96 T.lua_setfield(L, -2, to_luastring(name));
97 };
98
99 // app.*
100 T.lua_newtable(L);
101 setFn('go', (Ls) => {
102 h.go(Math.max(0, Math.floor(readValue(Ls, 1) || 1) - 1));
103 return 0;
104 });
105 setFn('next', () => (h.next(), 0));
106 setFn('prev', () => (h.prev(), 0));
107 setFn('play', (Ls) => (h.play(jsString(Ls, 1)), 0));
108 setFn('stop', (Ls) => (h.stop(jsString(Ls, 1)), 0));
109 setFn('volume', (Ls) => (h.volume(jsString(Ls, 1), readValue(Ls, 2)), 0));
110 setFn('music', (Ls) => (h.music(jsString(Ls, 1)), 0));
111 setFn('musicPlay', () => (h.musicPlay(), 0));
112 setFn('musicStop', () => (h.musicStop(), 0));
113 setFn('musicVolume', (Ls) => (h.musicVolume(readValue(Ls, 1)), 0));
114 setFn('videoPlay', (Ls) => (h.videoPlay(jsString(Ls, 1)), 0));
115 setFn('videoPause', (Ls) => (h.videoPause(jsString(Ls, 1)), 0));
116 setFn('videoRestart', (Ls) => (h.videoRestart(jsString(Ls, 1)), 0));
117 setFn('videoSeek', (Ls) => (h.videoSeek(jsString(Ls, 1), readValue(Ls, 2)), 0));
118 setFn('slide', (Ls) => (T.lua_pushnumber(Ls, h.currentSlide()), 1));
119 setFn('log', (Ls) => (h.log(jsString(Ls, 1)), 0));
120 T.lua_setglobal(L, to_luastring('app'));
121
122 // vars
123 T.lua_newtable(L);
124 T.lua_setglobal(L, to_luastring('vars'));
125
126 function setVars(obj = {}) {
127 T.lua_getglobal(L, to_luastring('vars'));
128 for (const key of Object.keys(obj)) {
129 pushValue(L, obj[key]);
130 T.lua_setfield(L, -2, to_luastring(key));
131 }
132 T.lua_pop(L, 1);
133 }
134
135 function getVars() {
136 const result = {};
137 T.lua_getglobal(L, to_luastring('vars'));
138 const tableIndex = T.lua_gettop(L);
139 T.lua_pushnil(L);
140 while (T.lua_next(L, tableIndex) !== 0) {
141 const key = T.lua_tostring(L, -2);
142 if (key) result[to_jsstring(key)] = readValue(L, -1);
143 T.lua_pop(L, 1);
144 }
145 T.lua_pop(L, 1);
146 return result;
147 }
148
149 T.lua_getglobal(L, to_luastring('app'));
150 setFn('setVar', (Ls) => {
151 T.lua_getglobal(Ls, to_luastring('vars'));
152 pushValue(Ls, readValue(Ls, 2));
153 T.lua_setfield(Ls, -2, T.lua_tostring(Ls, 1));
154 T.lua_pop(Ls, 1);
155 return 0;
156 });
157 setFn('getVar', (Ls) => {
158 T.lua_getglobal(Ls, to_luastring('vars'));
159 T.lua_getfield(Ls, -1, T.lua_tostring(Ls, 1));
160 T.lua_remove(Ls, -2);
161 return 1;
162 });
163 T.lua_pop(L, 1);
164
165 // anim.* — кастомные анимации элементов и слайдов (Web Animations API на стороне хоста)
166 T.lua_newtable(L);
167 setFn('play', (Ls) => {
168 const target = jsString(Ls, 1);
169 const frames = T.lua_type(Ls, 2) === T.LUA_TTABLE ? tableToJs(Ls, 2) : {};
170 const opts = T.lua_type(Ls, 3) === T.LUA_TTABLE ? tableToJs(Ls, 3) : {};
171 h.animate(target, frames, opts);
172 return 0;
173 });
174 setFn('fadeIn', (Ls) => {
175 h.animate(jsString(Ls, 1), { opacity: [0, 1] }, { duration: readValue(Ls, 2) || 400, delay: readValue(Ls, 3) || 0 });
176 return 0;
177 });
178 setFn('fadeOut', (Ls) => {
179 h.animate(jsString(Ls, 1), { opacity: [1, 0] }, { duration: readValue(Ls, 2) || 400, delay: readValue(Ls, 3) || 0, fill: 'forwards' });
180 return 0;
181 });
182 setFn('clear', (Ls) => {
183 h.animateClear(jsString(Ls, 1));
184 return 0;
185 });
186 T.lua_setglobal(L, to_luastring('anim'));
187
188 // sleep(ms) — приостановка скрипта без блокировки браузера (корутина)
189 T.lua_pushcfunction(L, (Ls) => luaYield(Ls, 1));
190 T.lua_setglobal(L, to_luastring('sleep'));
191
192 // Запуск кода в корутине: sleep уходит в setTimeout и возобновляет тред.
193 function pump(co, status, label) {
194 if (status === T.LUA_YIELD) {
195 const ms = Math.max(0, Math.round(T.lua_tonumber(co, -1) || 0));
196 setTimeout(() => pump(co, T.lua_resume(co, L, 0), label), ms);
197 return;
198 }
199 if (status !== T.LUA_OK) {
200 const err = T.lua_tostring(co, -1);
201 h.error(`Lua (${label}): ${err ? to_jsstring(err) : 'unknown error'}`);
202 }
203 T.lua_pop(L, 1); // убираем тред со стека основного состояния
204 }
205
206 function run(code, label = 'script') {
207 if (!code || !String(code).trim()) return getVars();
208 const loadStatus = lauxlib.luaL_loadstring(L, to_luastring(String(code)));
209 if (loadStatus !== T.LUA_OK) {
210 const err = T.lua_tostring(L, -1);
211 h.error(`Lua (${label}): ${err ? to_jsstring(err) : 'unknown error'}`);
212 T.lua_pop(L, 1);
213 return getVars();
214 }
215 const co = T.lua_newthread(L); // L: [fn, co]
216 T.lua_pushvalue(L, -2); // L: [fn, co, fn]
217 T.lua_xmove(L, co, 1); // fn уходит в корутину
218 T.lua_remove(L, -2); // L: [co]
219 pump(co, T.lua_resume(co, L, 0), label);
220 return getVars();
221 }
222
223 // Вычислить Lua-выражение и вернуть JS-значение.
224 // Используется редактором для кастомных элементов: return { style = {...}, html = '...' }.
225 function evaluate(code, label = 'eval') {
226 if (!code || !String(code).trim()) return null;
227 const status = lauxlib.luaL_loadstring(L, to_luastring(String(code)));
228 if (status !== T.LUA_OK) {
229 const err = T.lua_tostring(L, -1);
230 h.error(`Lua (${label}): ${err ? to_jsstring(err) : 'syntax error'}`);
231 T.lua_pop(L, 1);
232 return null;
233 }
234 const callStatus = T.lua_pcall(L, 0, 1, 0);
235 if (callStatus !== T.LUA_OK) {
236 const err = T.lua_tostring(L, -1);
237 h.error(`Lua (${label}): ${err ? to_jsstring(err) : 'runtime error'}`);
238 T.lua_pop(L, 1);
239 return null;
240 }
241 const value = valueToJs(L, -1);
242 T.lua_pop(L, 1);
243 return value;
244 }
245
246 function reset(obj = {}) {
247 T.lua_newtable(L);
248 T.lua_setglobal(L, to_luastring('vars'));
249 setVars(obj);
250 }
251
252 reset(hooks.vars || {});
253
254 return { run, getVars, setVars, reset, eval: evaluate };
255 }
256
257 window.createLuaRuntime = createRuntime;
258})();