Game Development Community

Best Associative Array (Hash Map / Dictionary) in TorqueScript?

by Charlie Patterson · in Torque Game Builder · 07/08/2011 (10:13 pm) · 4 replies

I'm wondering what others are using when they need a "Map" data structure in TorqueScript. You know, where you can define your own keys like

map[3] = object;
map["red"] = object2;
map[object3] = object4;

I realize that I can search through a SimSet one element at a time looking for what I put in there somewhere, but that is unattractive and error-prone. I'm getting into some of the more esoteric parts of my code, such as basic AI and message broadcasting, and I prefer to stay in TorqueScript and not to switch to C++.

So what are others doing for all their map-like needs?

P.S. This is the best article on it from 2005, and it ends up with no answers: http://www.garagegames.com/community/forums/viewthread/33773

#1
07/09/2011 (9:35 am)
Though somehow limited on usable key values, TS object's field lookup can be used for really simple and cheap mapping.

function cMap::get(%this, %key) {
    %unit = %this @ "." @ %key;

    %value = eval("return (" @ %unit @ ");");

    return %value;
}

function cMap::set(%this, %key, %value) {
    %unit = %this @ "." @ %key;

    eval(%unit @ "=" @ %value @ ";");
}

Then, string keys can probably be used too if you wrap them with object first.
#2
07/09/2011 (4:42 pm)
That's really clever!

In other words, if you didn't need an API like you wrote, I could just say:

%map = new SimObject();
%map.key1 = value1;
%map.key2 = value2;

someFunction(%map.key2);

If I want to iterate, that may even be possible:

%count = %map.getDynamicFieldCount();
%pair = %map.getDynamicField(0);

Still, I was hoping for something a little more natural.
#3
07/10/2011 (3:59 pm)
Not sure I understand what you mean by natural. Maps were never too natural to my taste, they are alien to every numeric language out there. TS however operates on strings, every object here by and large _is_ a map. Without an API it's just normal field access. Can't get more natural than that I think.
#4
07/10/2011 (10:35 pm)
@Rpahut, I would counter that most scripting languages have maps/associative arrays at the core: Perl, Ruby, Python, Lua (via tables), etc. Perhaps I really don't need them in the domain of game programming, but they are widely supported in scripting languages, often as *the* base non-scalar type. Hell even the unix shell makes a poor stab at it!

Arrays and maps show up all the time when I'm programming. Even Java/C++ provide them as standard libraries.

I could try to write up an example need for it, but I'm not feeling particularly creative at the moment. I just don't think that I can keep a SimSet of things and look them up by any key (atleast not based on the docs).