Lua: Persistent variables
Add a way for the lua scripts to set and retrieve variables that are persistent - saved and restored with the game. Invalidates saves.
This commit is contained in:
@@ -4,6 +4,15 @@
|
||||
-- This file contains lua code used by NetHack core.
|
||||
-- Is it loaded once, at game start, and kept in memory until game exit.
|
||||
|
||||
-- Data in nh_lua_variables table can be set and queried with nh.variable()
|
||||
-- This table is saved and restored along with the game.
|
||||
nh_lua_variables = {
|
||||
};
|
||||
|
||||
-- wrapper to simplify calling from nethack core
|
||||
function get_variables_string()
|
||||
return "nh_lua_variables=" .. table_stringify(nh_lua_variables) .. ";";
|
||||
end
|
||||
|
||||
-- This is an example of generating an external file during gameplay,
|
||||
-- which is updated periodically.
|
||||
|
||||
@@ -107,3 +107,35 @@ end
|
||||
function pline(fmt, ...)
|
||||
nh.pline(string.format(fmt, table.unpack({...})));
|
||||
end
|
||||
|
||||
-- wrapper to make calling from nethack core easier
|
||||
function nh_set_variables_string(key, tbl)
|
||||
return "nh_lua_variables[\"" .. key .. "\"]=" .. table_stringify(tbl) .. ";";
|
||||
end
|
||||
|
||||
-- wrapper to make calling from nethack core easier
|
||||
function nh_get_variables_string(tbl)
|
||||
return "return " .. table_stringify(tbl) .. ";";
|
||||
end
|
||||
|
||||
-- return the (simple) table tbl converted into a string
|
||||
function table_stringify(tbl)
|
||||
local str = "";
|
||||
for key, value in pairs(tbl) do
|
||||
local typ = type(value);
|
||||
if (typ == "table") then
|
||||
str = str .. "[\"" .. key .. "\"]=" .. table_stringify(value);
|
||||
elseif (typ == "string") then
|
||||
str = str .. "[\"" .. key .. "\"]=[[" .. value .. "]]";
|
||||
elseif (typ == "boolean") then
|
||||
str = str .. "[\"" .. key .. "\"]=" .. tostring(value);
|
||||
elseif (typ == "number") then
|
||||
str = str .. "[\"" .. key .. "\"]=" .. value;
|
||||
elseif (typ == "nil") then
|
||||
str = str .. "[\"" .. key .. "\"]=nil";
|
||||
end
|
||||
str = str .. ",";
|
||||
end
|
||||
-- pline("table_stringify:(%s)", str);
|
||||
return "{" .. str .. "}";
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user