80 lines
2.4 KiB
Lua
80 lines
2.4 KiB
Lua
local util = require("itteutil")
|
|
|
|
-- Default settings
|
|
local folia = {
|
|
foils_dir = "",
|
|
debug = false,
|
|
}
|
|
|
|
|
|
util.docs.get_foils = [[ (directory_str)
|
|
Given the full path to a directory of foils, return the foil contents as a
|
|
table.
|
|
]]
|
|
function folia.get_foils(str)
|
|
local foil_list_str = io.popen("ls " .. str)
|
|
local foils = {}
|
|
if foil_list_str then
|
|
local foil_list = util.split_str(foil_list_str:read("*a"))
|
|
for i = 1, #foil_list do
|
|
local key = string.gsub(foil_list[i], ".lua", "")
|
|
local func, err = loadfile(str .. "/" .. foil_list[i])
|
|
if func then
|
|
func()
|
|
foils[key] = grammar
|
|
end
|
|
end
|
|
-- Unset global variables
|
|
func = nil
|
|
grammar = nil
|
|
end
|
|
return foils
|
|
end
|
|
|
|
|
|
util.docs.output = [[ (key_str)
|
|
Given a foil name or foils table key, output a random expanded string.
|
|
]]
|
|
function folia.output(key)
|
|
local foils = folia.get_foils(folia.foils_dir)
|
|
if table.concat(util.table_keys(foils), "") == "" then
|
|
util.debug("output", "Error: cannot retrieve foils." ..
|
|
" Please make sure the full directory path is correct.", folia.debug)
|
|
do return end
|
|
elseif not util.has_key(foils, key) then
|
|
util.debug("output", "Error: the key `" .. key ..
|
|
"` is not in the foils table.", folia.debug)
|
|
do return end
|
|
elseif not util.has_key(foils[key], "origin") then
|
|
util.debug("output", "Error: no origin found in the foil.", folia.debug)
|
|
do return end
|
|
elseif foils[key]["origin"] == {} then
|
|
util.debug("output", "Error: empty origin.", folia.debug)
|
|
do return end
|
|
end
|
|
|
|
local output_str = util.pick(foils[key]["origin"])[1]
|
|
local pattern = "#(%w+)#"
|
|
util.debug("output", "level 1: " .. output_str, folia.debug)
|
|
-- Check for expansion objects and replace them until none are found
|
|
while string.find(output_str, pattern) ~= nil do
|
|
local hash = output_str:sub(string.find(output_str, pattern))
|
|
local obj = hash:sub(2, #hash - 1)
|
|
-- Check the object key is in the foil grammar, and replace one instance
|
|
-- at a time.
|
|
if util.has_key(foils[key], obj) then
|
|
local expand_str = util.pick(foils[key][obj])[1]
|
|
output_str = string.gsub(output_str, hash, expand_str, 1)
|
|
util.debug("output", "level n: " .. output_str, folia.debug)
|
|
-- If the object key is not in the grammar, replace references with a
|
|
-- placeholder.
|
|
else
|
|
output_str = string.gsub(output_str, hash, "[" .. obj .. "]")
|
|
end
|
|
end
|
|
return output_str
|
|
end
|
|
|
|
|
|
return folia
|