From f052b00bd2658dafd4d61209e9fa3e8b328126f0 Mon Sep 17 00:00:00 2001 From: iamcheeseman Date: Fri, 20 Mar 2026 08:45:50 -0400 Subject: add a function to export to lua --- src/export.lua | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/init.lua | 1 + 2 files changed, 59 insertions(+) create mode 100644 src/export.lua (limited to 'src') diff --git a/src/export.lua b/src/export.lua new file mode 100644 index 0000000..f3713af --- /dev/null +++ b/src/export.lua @@ -0,0 +1,58 @@ +local INDENT_STR = " " + +local function str_to_source(str) + return "\"" .. str .. "\"" +end + +local function table_to_str(tbl, indent) + indent = indent or 1 + + -- to prevent people doing stuff that this function doesn't expect + assert(not getmetatable(tbl), "cannot export a table with a metatable") + + local src = "{" + for k, v in pairs(tbl) do + print(k, v) + if type(k) == "function" or type(v) == "function" then + error("Cannot export function " .. tostring(k) .. " = " .. tostring(v)) + end + if type(k) ~= "number" then + src = src .. "[" + + if type(k) == "string" then + src = src .. str_to_source(k) + elseif type(k) == "table" then + error("Tables as keys aren't supported for exporting") + else + src = src .. tostring(k) + end + + src = src .. "]=" + end + + if type(v) == "table" then + src = src .. table_to_str(v, indent + 1) + elseif type(v) == "string" then + src = src .. str_to_source(v) + else + src = src .. tostring(v) + end + + src = src .. "," + end + + src = src .. "}" + + return src +end + +function export_to_source(tbl, file_name) + local src = table_to_str(tbl) + src = "return " .. src + local file = io.open(file_name, "w") + if file == nil then + error("could not open file '" .. file_name "'") + end + file:write(src) + file:close() +end diff --git a/src/init.lua b/src/init.lua index ec71521..9ecda05 100644 --- a/src/init.lua +++ b/src/init.lua @@ -8,6 +8,7 @@ require "src.sprite" require "src.state_machine" require "src.im" require "src.room_editor" +require "src.export" SCR_WIDTH = 320 SCR_HEIGHT = 180 -- cgit v1.3-2-g0d8e