• Hey Guest! Ever feel like entering a Game Jam, but the time limit is always too much pressure? We get it... You lead a hectic life and dedicating 3 whole days to make a game just doesn't work for you! So, why not enter the GMC SLOW JAM? Take your time! Kick back and make your game over 4 months! Interested? Then just click here!

Is there any efficient way to register "GET/SET function" pair for object's member variable?

Zhanghua

Member
Is there any way to register "GET/SET function" pair for object's member variable?
I implement this as following, but think that isn't efficient and is ugly...., cause the Syntax isn't closure.
GML:
//Global Script
function ObjMakeVariable(obj,name,val){
    with(obj){
        var env = { scope: id, name: name };
        variable_instance_set(id,name,val);
        variable_instance_set(id,"get"+name,method(env,function(){
            return variable_instance_get(scope,name);
        }));
      
        variable_instance_set(id,"set"+name,method(env,function(v){
            variable_instance_set(scope,name,v);
        }));
    }
}

//You can utilize this in the Object create event like this
ObjMakeVariable(id,"abc",1);
setabc(123);
show_message(  getabc() );
 

Zhanghua

Member
GML:
get_thing = function() {...};
set_thing = function(...) {...};
That's the most efficient way, at least from a performance standpoint. ;)

Not everything that can be automated should be automated.
Yes, you are right......., I just immigrate the JAVA code which uses the package "lombok", and seek something like this.
 

Alice

Darts addict
Forum Staff
Moderator
Is there a specific reason why you need to declare get/set methods like this?
I know things are done like this in Java, but perhaps one of the most important things about programming in different languages is that concepts from one language don't really apply to others.

In this specific case, getter/setter methods in Java are meant to achieve encapsulation - i.e. exposing no more functionality than needed by external code. However, it doesn't translate well to GML with its loose types and dynamically changed structures. So instead of making getVariable/setVariable functions the Java way, I'd instead recommend opting for GML way:
GML:
id.abc = 1; // or just abc = 1
abc = 123;
show_message(abc);
Getter/setter are more justifiable for non-trivial getting/setting - e.g. getArea() which computes result of (right - left) * (bottom - top), or setWidth(value) which sets right = left + value
Other than these? Excluding consistency reasons, I'd just access the variable directly.*

Also, I suggest reading this thread, which touches upon the same dilemma.

*Then again, I come from C# world which has syntactic sugar for wrapping getter/setter methods in properties and accessing them like plain fields. Thus, the syntax like "show_message(obj.variable)" or "obj.variable = value" feel familiar and not out of place at all.
 
Top