Jump to content


Xpis

Member Since 11 Mar 2008
Offline Last Active May 01 2008 09:41 AM

Posts I've Made

In Topic: Gml And C++ (reference,vector, & Pointers)

11 March 2008 - 03:40 PM

Now a new question arises.

if a vector is similar to a ds_list or a ds_stack how can I pass that list to a function (the whole list or stack) but not make it global? is the list or stack local only to the object if I do not make it global?

And if someone could clear up more about the reference and vector questions that would be helpful as well

<{POST_SNAPBACK}>


Better late than never...

Well, I've recently come back to GML after doing some "real" programming (including C++).

I think the closest GML gets to pointers and whatnot is when you create stuff. For example,

this = ds_list_create();

(you'll probably cringe at using "this" as a variable name, but it illustrates my point!)

In the example, you've created a ds_list, and stored it in the variable "this". But what have you actually done? Well, you've created a ds_list (with the call to ds_list_create) and stored the id of this list in "this". Yep, it's a pointer.

So, when you think about it, when you call a function such as

ds_list_add(this,"Item");

you are, in fact passing a pointer to a ds_list to the function. If you print out the value of this, it will be some sort of an integer; if you look at a pointer in C++, you see some sort of hex number. Both of these reference the memory point the value is stored in.

As for passing ds_ s to functions, it's really easy. All you do is pass the ds_ pointer to the function. So if you write a function to use your ds_list "this", you can simply write

function(this, other, args);

Note, this is exactly the same as

int i = function(list&, other, args);

so if you alter "this" in the function, you alter "this" in "real life" as well!

In case you haven't worked it out already, a ds_list is the equivalent of a std::vector. So you can do

{
          var this;
          this = ds_list_create(); 
          ds_list_add(this,"Sword"); // push_back()
          
          ds_list_delete(this, ds_list_size(this) - 1);                // pop_back()
          
          ds_list_delete(this, 4); // They always begin at 0

          ds_list_destroy(this); // No auto-garbage collection, so remember to free
                                         // your ds_s when you've finished with them
}

Hope that helps

Xpis

PS. If you want an example of a game which uses ds_s gratuitously, email me.