Last active
September 23, 2025 00:31
-
-
Save Rayquaza01/e2cedb3ab53d166fdcd2c1a9cc950b1e to your computer and use it in GitHub Desktop.
Picotron INI Parser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| --- Loads an ini string into a lua table | |
| --- @param ini_text string | |
| --- @return table | |
| function load_ini(ini_text) | |
| local tbl = {} | |
| local lines = split(ini_text, "\n", false) | |
| local current_head = tbl | |
| local header = "" | |
| for l in all(lines) do | |
| -- if line is not comment | |
| if not (l == "" or l:find("^%s*;") or l:find("^%s*%-%-") or l:find("^%s*#") or l:find("^%s*//")) then | |
| if l:find("^%[.+%]$") then | |
| current_head = tbl | |
| header = l:sub(2, #l - 1) | |
| for h in all(split(header, ".", false)) do | |
| if tonum(h) ~= nil then | |
| h = tonum(h) | |
| end | |
| if (current_head[h]) == nil then | |
| current_head[h] = {} | |
| end | |
| current_head = current_head[h] | |
| end | |
| elseif l:find("^%w+=.+") then | |
| local equals_pos = l:find("=", 1, true) | |
| local key = l:sub(1, equals_pos - 1) | |
| local value = l:sub(equals_pos + 1, #l) | |
| if tonum(key) ~= nil then | |
| key = tonum(key) | |
| end | |
| if tonum(value) ~= nil then | |
| value = tonum(value) | |
| elseif value == "true" or value == "false" then | |
| value = unpod(value) | |
| else | |
| value = unpod(value) or value | |
| end | |
| current_head[key] = value | |
| end | |
| end | |
| end | |
| return tbl | |
| end | |
| --- Dumps a lua table into an ini string | |
| --- @param tbl table | |
| --- @param header_prefix? string | |
| --- @return string | |
| function dump_ini(tbl, header_prefix) | |
| if header_prefix == nil or type(header_prefix) ~= "string" then | |
| header_prefix = "" | |
| end | |
| local text = {} | |
| -- first pass add any values | |
| for key, value in pairs(tbl) do | |
| if type(value) ~= "table" then | |
| add(text, ("%s=%s"):format(tostr(key), pod(value))) | |
| end | |
| end | |
| -- second pass add nested tables | |
| for key, value in pairs(tbl) do | |
| if type(value) == "table" then | |
| add(text, ("[%s%s]"):format(header_prefix, key)) | |
| add(text, dump_ini(value, ("%s%s."):format(header_prefix, key))) | |
| end | |
| end | |
| return table.concat(text, "\n") | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment