Phantasmal MUD Lib for DGD
|
Phantasmal Site > DGD > DGD Reference Manual (legacy) > Mappings 3.8 MappingsMappings are data structures, rather like arrays. An array is a sequence of values (often numbers). A mapping is a sort of dictionary of values, so that you can find a value by looking up its name, called a key. You'll see mappings called hash tables in some other languages. Let's say we wanted to look through an array of strings and make sure there were no repeated elements. Specifically, we wanted to read through an array and return another array which had no repeated elements, so every value was unique. string *unique(string *array) { mapping elements; int ctr; elements = ([ ]); for(ctr = 0; ctr < sizeof(array); ctr++) { elements[array[ctr]] = 1; } return map_indices(elements); } Notice that mapping is used like int to declare variables. Notice also that we have to initialize the mapping to a new empty value before we assign anything to it. A mapping in LPC is written almost, but not quite, like an
array. The mapping Try compiling a new /usr/admin/myobj.c with the function above in it. This can be instead of the old function, or in addition to it. Once you've successfully compiled myobj.c, try typing "/usr/admin/myobj"->unique( ({ "bob", "sam", "murray", "bob" }) ). You should get a result like $45 = ({ "bob", "murray", "sam" }). The result contains all the same strings as the original, but in a different order, and with no repeated "bob". You've just called your function on the object, but you didn't use quite the same syntax you've been using. Instead, you used the object's name in double quotes. The object's name is the same as the filename, but without the .c on the end. The function first makes a new, empty mapping, and then puts each element of the array into it as a key, also called an index. It assigns the value 1 to each key, though the value won't actually be used. Any repeated array elements will just assign 1 to the same key that's already in the array. Then, at the end, we call a function called map_indices which returns an array of the indices (keys) of the mapping, in alphabetical order.
|