An idea came up recently in a thread on Gamedev.net about scripting where someone made the statement that Lua tables would be more convenient for storing data than would XML. I don't have any idea as to the veracity of that statement, but I do know two things:
Since I was looking for an excuse to try out Lua and I don't have a great big project that I want to hook it up with right now, I thought that maybe I'd see about going from my preferred data intermediary (XML) to the poster's suggestion (tables in Lua).
Lua is a C-like scripting language that's become popular in game development. Part of the reason for the popularity of Lua is its free open source license. Another part of the popularity comes from the easy interaction with a C or C++ project. Apparently it's also easier to program in than C.
XSLT is the extensible stylesheet transform language. XSLT can be used for processing data that's stored as XML and turning it in to other XML formats, HTML or text. I've talked about XSLT here before.
I started by downloading the Lua source and building it. After that I had a
lua executable. Running Lua interactively gives a simple shell. Using that I can type in a Lua expression and see the result. So I poked around a bit and flipped through the manual.
I wrote up an XML file that lists some items you might find in a hardware store. The file contains lists of items. Each list is represented by an <items /> element. This element has a category attribute. Inside the <items /> element are <item /> elements. Each item has a name, a price and a quantity (the number the hardware store has in stock) as attributes.
Here's what my XML looks like:
apply-templatesstatement causes other templates (in the XSLT) to be used to match other nodes (in the XML source). After all the nodes have been processed, the closing "}" is emitted.
with-paramelement to any templates that are called by
@quantitystatements are replaced by the values of each of those attributes for the item being processed. The
$categorystatement gets the value of the category parameter that was passed from the items template.
Here's what the generated Lua file looks like:
So if you want to get some XML data into your Lua script without having to actually parse the XML yourself, you could use code like this. Note that this kind of code generation only makes sense if you were going to load up most of XML data structure into a Lua object anyway. If you have a monstrous XML file and only want to use a few lines of it, then this is going to be horrendously inefficient. In that case you're far better off parsing the XML in your application and giving Lua an access function to get the data that it needs.