259 lines
9.1 KiB
JavaScript
259 lines
9.1 KiB
JavaScript
// Мост Lua ↔ JS для интерактивных презентаций.
|
|
// Использует глобальный fengari (vendor/fengari-web.js).
|
|
// Скрипты выполняются в корутине: доступен sleep(ms), анимации через таблицу anim.
|
|
(function () {
|
|
const { lua, lauxlib, lualib, to_luastring, to_jsstring } = window.fengari;
|
|
const T = lua;
|
|
const luaYield = T.lua_yield || ((Ls, n) => T.lua_yieldk(Ls, n, null, null));
|
|
|
|
function readValue(L, idx) {
|
|
const type = T.lua_type(L, idx);
|
|
if (type === T.LUA_TBOOLEAN) return !!T.lua_toboolean(L, idx);
|
|
if (type === T.LUA_TNUMBER) return T.lua_tonumber(L, idx);
|
|
if (type === T.LUA_TSTRING) {
|
|
const s = T.lua_tostring(L, idx);
|
|
return s ? to_jsstring(s) : '';
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function tableToJs(L, idx) {
|
|
const abs = T.lua_absindex(L, idx);
|
|
const len = T.lua_rawlen(L, abs);
|
|
if (len > 0) {
|
|
const arr = [];
|
|
for (let i = 1; i <= len; i += 1) {
|
|
T.lua_rawgeti(L, abs, i);
|
|
arr.push(valueToJs(L, -1));
|
|
T.lua_pop(L, 1);
|
|
}
|
|
return arr;
|
|
}
|
|
const obj = {};
|
|
T.lua_pushnil(L);
|
|
while (T.lua_next(L, abs) !== 0) {
|
|
const key = readValue(L, -2);
|
|
obj[key === null ? '' : String(key)] = valueToJs(L, -1);
|
|
T.lua_pop(L, 1);
|
|
}
|
|
return obj;
|
|
}
|
|
|
|
function valueToJs(L, idx) {
|
|
const type = T.lua_type(L, idx);
|
|
if (type === T.LUA_TTABLE) return tableToJs(L, idx);
|
|
return readValue(L, idx);
|
|
}
|
|
|
|
function pushValue(L, value) {
|
|
if (typeof value === 'number' && Number.isFinite(value)) T.lua_pushnumber(L, value);
|
|
else if (typeof value === 'boolean') T.lua_pushboolean(L, value);
|
|
else if (typeof value === 'string') T.lua_pushstring(L, to_luastring(value));
|
|
else T.lua_pushnil(L);
|
|
}
|
|
|
|
function jsString(L, idx) {
|
|
const s = T.lua_tostring(L, idx);
|
|
return s ? to_jsstring(s) : '';
|
|
}
|
|
|
|
function createRuntime(hooks = {}) {
|
|
const L = lauxlib.luaL_newstate();
|
|
lualib.luaL_openlibs(L);
|
|
|
|
const noop = () => {};
|
|
const h = {
|
|
go: hooks.go || noop,
|
|
next: hooks.next || noop,
|
|
prev: hooks.prev || noop,
|
|
play: hooks.play || noop,
|
|
stop: hooks.stop || noop,
|
|
volume: hooks.volume || noop,
|
|
music: hooks.music || noop,
|
|
musicPlay: hooks.musicPlay || noop,
|
|
musicStop: hooks.musicStop || noop,
|
|
musicVolume: hooks.musicVolume || noop,
|
|
videoPlay: hooks.videoPlay || noop,
|
|
videoPause: hooks.videoPause || noop,
|
|
videoRestart: hooks.videoRestart || noop,
|
|
videoSeek: hooks.videoSeek || noop,
|
|
currentSlide: hooks.currentSlide || (() => 1),
|
|
animate: hooks.animate || noop,
|
|
animateClear: hooks.animateClear || noop,
|
|
log: hooks.log || ((msg) => console.log('[lua]', msg)),
|
|
error: hooks.error || ((msg) => console.error('[lua]', msg)),
|
|
};
|
|
|
|
const setFn = (name, fn) => {
|
|
T.lua_pushcfunction(L, (state) => {
|
|
try {
|
|
return fn(state) || 0;
|
|
} catch (err) {
|
|
h.error(String(err && err.message ? err.message : err));
|
|
return 0;
|
|
}
|
|
});
|
|
T.lua_setfield(L, -2, to_luastring(name));
|
|
};
|
|
|
|
// app.*
|
|
T.lua_newtable(L);
|
|
setFn('go', (Ls) => {
|
|
h.go(Math.max(0, Math.floor(readValue(Ls, 1) || 1) - 1));
|
|
return 0;
|
|
});
|
|
setFn('next', () => (h.next(), 0));
|
|
setFn('prev', () => (h.prev(), 0));
|
|
setFn('play', (Ls) => (h.play(jsString(Ls, 1)), 0));
|
|
setFn('stop', (Ls) => (h.stop(jsString(Ls, 1)), 0));
|
|
setFn('volume', (Ls) => (h.volume(jsString(Ls, 1), readValue(Ls, 2)), 0));
|
|
setFn('music', (Ls) => (h.music(jsString(Ls, 1)), 0));
|
|
setFn('musicPlay', () => (h.musicPlay(), 0));
|
|
setFn('musicStop', () => (h.musicStop(), 0));
|
|
setFn('musicVolume', (Ls) => (h.musicVolume(readValue(Ls, 1)), 0));
|
|
setFn('videoPlay', (Ls) => (h.videoPlay(jsString(Ls, 1)), 0));
|
|
setFn('videoPause', (Ls) => (h.videoPause(jsString(Ls, 1)), 0));
|
|
setFn('videoRestart', (Ls) => (h.videoRestart(jsString(Ls, 1)), 0));
|
|
setFn('videoSeek', (Ls) => (h.videoSeek(jsString(Ls, 1), readValue(Ls, 2)), 0));
|
|
setFn('slide', (Ls) => (T.lua_pushnumber(Ls, h.currentSlide()), 1));
|
|
setFn('log', (Ls) => (h.log(jsString(Ls, 1)), 0));
|
|
T.lua_setglobal(L, to_luastring('app'));
|
|
|
|
// vars
|
|
T.lua_newtable(L);
|
|
T.lua_setglobal(L, to_luastring('vars'));
|
|
|
|
function setVars(obj = {}) {
|
|
T.lua_getglobal(L, to_luastring('vars'));
|
|
for (const key of Object.keys(obj)) {
|
|
pushValue(L, obj[key]);
|
|
T.lua_setfield(L, -2, to_luastring(key));
|
|
}
|
|
T.lua_pop(L, 1);
|
|
}
|
|
|
|
function getVars() {
|
|
const result = {};
|
|
T.lua_getglobal(L, to_luastring('vars'));
|
|
const tableIndex = T.lua_gettop(L);
|
|
T.lua_pushnil(L);
|
|
while (T.lua_next(L, tableIndex) !== 0) {
|
|
const key = T.lua_tostring(L, -2);
|
|
if (key) result[to_jsstring(key)] = readValue(L, -1);
|
|
T.lua_pop(L, 1);
|
|
}
|
|
T.lua_pop(L, 1);
|
|
return result;
|
|
}
|
|
|
|
T.lua_getglobal(L, to_luastring('app'));
|
|
setFn('setVar', (Ls) => {
|
|
T.lua_getglobal(Ls, to_luastring('vars'));
|
|
pushValue(Ls, readValue(Ls, 2));
|
|
T.lua_setfield(Ls, -2, T.lua_tostring(Ls, 1));
|
|
T.lua_pop(Ls, 1);
|
|
return 0;
|
|
});
|
|
setFn('getVar', (Ls) => {
|
|
T.lua_getglobal(Ls, to_luastring('vars'));
|
|
T.lua_getfield(Ls, -1, T.lua_tostring(Ls, 1));
|
|
T.lua_remove(Ls, -2);
|
|
return 1;
|
|
});
|
|
T.lua_pop(L, 1);
|
|
|
|
// anim.* — кастомные анимации элементов и слайдов (Web Animations API на стороне хоста)
|
|
T.lua_newtable(L);
|
|
setFn('play', (Ls) => {
|
|
const target = jsString(Ls, 1);
|
|
const frames = T.lua_type(Ls, 2) === T.LUA_TTABLE ? tableToJs(Ls, 2) : {};
|
|
const opts = T.lua_type(Ls, 3) === T.LUA_TTABLE ? tableToJs(Ls, 3) : {};
|
|
h.animate(target, frames, opts);
|
|
return 0;
|
|
});
|
|
setFn('fadeIn', (Ls) => {
|
|
h.animate(jsString(Ls, 1), { opacity: [0, 1] }, { duration: readValue(Ls, 2) || 400, delay: readValue(Ls, 3) || 0 });
|
|
return 0;
|
|
});
|
|
setFn('fadeOut', (Ls) => {
|
|
h.animate(jsString(Ls, 1), { opacity: [1, 0] }, { duration: readValue(Ls, 2) || 400, delay: readValue(Ls, 3) || 0, fill: 'forwards' });
|
|
return 0;
|
|
});
|
|
setFn('clear', (Ls) => {
|
|
h.animateClear(jsString(Ls, 1));
|
|
return 0;
|
|
});
|
|
T.lua_setglobal(L, to_luastring('anim'));
|
|
|
|
// sleep(ms) — приостановка скрипта без блокировки браузера (корутина)
|
|
T.lua_pushcfunction(L, (Ls) => luaYield(Ls, 1));
|
|
T.lua_setglobal(L, to_luastring('sleep'));
|
|
|
|
// Запуск кода в корутине: sleep уходит в setTimeout и возобновляет тред.
|
|
function pump(co, status, label) {
|
|
if (status === T.LUA_YIELD) {
|
|
const ms = Math.max(0, Math.round(T.lua_tonumber(co, -1) || 0));
|
|
setTimeout(() => pump(co, T.lua_resume(co, L, 0), label), ms);
|
|
return;
|
|
}
|
|
if (status !== T.LUA_OK) {
|
|
const err = T.lua_tostring(co, -1);
|
|
h.error(`Lua (${label}): ${err ? to_jsstring(err) : 'unknown error'}`);
|
|
}
|
|
T.lua_pop(L, 1); // убираем тред со стека основного состояния
|
|
}
|
|
|
|
function run(code, label = 'script') {
|
|
if (!code || !String(code).trim()) return getVars();
|
|
const loadStatus = lauxlib.luaL_loadstring(L, to_luastring(String(code)));
|
|
if (loadStatus !== T.LUA_OK) {
|
|
const err = T.lua_tostring(L, -1);
|
|
h.error(`Lua (${label}): ${err ? to_jsstring(err) : 'unknown error'}`);
|
|
T.lua_pop(L, 1);
|
|
return getVars();
|
|
}
|
|
const co = T.lua_newthread(L); // L: [fn, co]
|
|
T.lua_pushvalue(L, -2); // L: [fn, co, fn]
|
|
T.lua_xmove(L, co, 1); // fn уходит в корутину
|
|
T.lua_remove(L, -2); // L: [co]
|
|
pump(co, T.lua_resume(co, L, 0), label);
|
|
return getVars();
|
|
}
|
|
|
|
// Вычислить Lua-выражение и вернуть JS-значение.
|
|
// Используется редактором для кастомных элементов: return { style = {...}, html = '...' }.
|
|
function evaluate(code, label = 'eval') {
|
|
if (!code || !String(code).trim()) return null;
|
|
const status = lauxlib.luaL_loadstring(L, to_luastring(String(code)));
|
|
if (status !== T.LUA_OK) {
|
|
const err = T.lua_tostring(L, -1);
|
|
h.error(`Lua (${label}): ${err ? to_jsstring(err) : 'syntax error'}`);
|
|
T.lua_pop(L, 1);
|
|
return null;
|
|
}
|
|
const callStatus = T.lua_pcall(L, 0, 1, 0);
|
|
if (callStatus !== T.LUA_OK) {
|
|
const err = T.lua_tostring(L, -1);
|
|
h.error(`Lua (${label}): ${err ? to_jsstring(err) : 'runtime error'}`);
|
|
T.lua_pop(L, 1);
|
|
return null;
|
|
}
|
|
const value = valueToJs(L, -1);
|
|
T.lua_pop(L, 1);
|
|
return value;
|
|
}
|
|
|
|
function reset(obj = {}) {
|
|
T.lua_newtable(L);
|
|
T.lua_setglobal(L, to_luastring('vars'));
|
|
setVars(obj);
|
|
}
|
|
|
|
reset(hooks.vars || {});
|
|
|
|
return { run, getVars, setVars, reset, eval: evaluate };
|
|
}
|
|
|
|
window.createLuaRuntime = createRuntime;
|
|
})();
|