I was looking for a way to store object attribute data, and came up with this tiny class:
class cAttribFileWith the addition of a few simple parsing functions, this has actually been pretty useful.
{
public:
typedef std::string tID;
typedef std::string tVal;
typedef std::map<tID, tVal> tAttrib;
typedef std::map<tID, cAttribFile> tNode;
std::string &operator()(const std::string &s) { return mAttrib[s]; }
cAttribFile &operator[](const std::string &s) { return mNode[s]; }
tAttrib mAttrib;
tNode mNode;
};
In basic terms, each cAttribFile node has a set of named attributes (map from ID to Value), and a set of named nodes (map from ID to another cAttribFile).
This lets me parse a file like this, where an '=' defines a new attribute, and braces define a new node:
Name = ExplosionThen I can refer to this data like this:
MaxParticles = 50
Smoke
{
Duration = 1
Loop = false
InitialParticles = 5
Color
{
Type = Lerp
V0 = 1,0.5,0,1
V1 = 1,0.5,0,0
}
}
duration = attr_file["Smoke"]("Duration");where [] operations refer to nodes and () operations refer to attributes.
color_interpolation = attr_file["Smoke"]["Color"]("Type");
Adding some iterators over attributes/nodes makes this very flexible.
OK, so it's not ALL that exciting, but it's a very simple class and file format that can be used to hold all sorts of data, without the mind-numbing aesthetics of an XML file.
Very cool Craig! I like the syntax for getting attributes; very clever use of operator overloading in C++.
ReplyDeleteHow do you handle types? Since everything comes in as a string, I assume the calling code does the casting manually?
Thanks! Yes - keeping everything as a string makes it really easy to work with, and it's pretty easy to convert to pretty much anything else with a simple library of functions - int, float, bool, vector, quaternion, color, etc.
ReplyDelete