-- Shared helpers. Savestate create/load only works inside an exec memory callback in Mesen2 2.1.1. local M = {} function M.onNextExec(fn) local id id = emu.addMemoryCallback(function() if id then emu.removeMemoryCallback(id, emu.callbackType.exec, 0, 0xFFFFFF); local f = fn; fn = nil; id = nil; if f then f() end end end, emu.callbackType.exec, 0, 0xFFFFFF) end function M.load(path, after) M.onNextExec(function() local h = io.open(path, "rb"); emu.loadSavestate(h:read("a")); h:close(); if after then after() end end) end function M.save(path) M.onNextExec(function() local h = io.open(path, "wb"); h:write(emu.createSavestate()); h:close() end) end function M.pc() local s = emu.getState(); return s["cpu.k"] * 0x10000 + s["cpu.pc"] end function M.wram(lo, n) local t = {} for i = 0, n - 1 do t[#t + 1] = string.char(emu.read(lo + i, emu.memType.snesWorkRam)) end return table.concat(t) end -- input plan: "frame:btn+btn[/hold],..." ; default hold 4 frames function M.plan(str) local p = {} for f, b, hold in (str or ""):gmatch("(%d+):([%w+]+)/?(%d*)") do p[tonumber(f)] = {b, tonumber(hold) or 4} end return p end -- wrap fn so Lua errors get written to $TBG_ERR (testrunner swallows them) function M.guard(fn) return function(...) local ok, e = pcall(fn, ...) if not ok then local h = io.open(os.getenv("TBG_ERR") or "/home/siege/Projects/tbg/re/runs/lua_err.txt", "a"); h:write(tostring(e), "\n"); h:close(); emu.stop(99) end end end return M