editing.lua

1
classes_editable = setmetatable({}, {__mode = "v", __index = function (t, k) return GetEditableClass(k) or {}; end, __newindex = function (t, k, v) return SaveEditableClass(k, v); end });
2
moobox = moobox or {};
3
 
4
--Load it from file
5
function GetEditableClass(name)
6
	local subenv = { classes = { } }
7
	local classdefinition = loadfile("objects/"..param..".lua");
8
	setfenv(classdefinition, subenv);
9
	local success, message = pcall(classdefinition);
10
	if not success then return message or "Unkown error reading class"
11
	else return subenv.class; end
12
end
13
 
14
--Save it to file
15
function SaveEditableClass(name, t)
16
	function writetable(filename, t)
17
		local f = io.open(filename, "w+");
18
		if not f then return nil; end
19
		for k, v in pairs(t) do
20
			if type(v) == "string" then
21
				f:write(string.format("class[\"%s\"] = \"%s\";\n", k, v));
22
			end
23
		end
24
	end
25
	
26
	local success, message = pcall(writetable, string.format("editor/%s.dat", name), t);
27
	if not success then return message; end
28
	return nil;
29
end
30
 
31
--Compile (and the compiled class goes to classes[name]
32
function CompileEditableClass(t)
33
	if not t then return "Error compiling... no (or invalid) class specified"; end
34
	local compiled = {};
35
	for k, v in pairs(t) do
36
		local success, compiledverb = pcall(loadstring, v);
37
		if not success then return "Error compiling verb '"..k.."': "..(compiledverb or "Unkown error"); end
38
		compiled[k] = (compiledverb and setfenv(compiledverb, verbbox)) or nil;
39
	end
40
	return compiled;
41
end