Using With or Named Instance?

piranha305

Member
I am trying to figure out what the best approach is i have a manager instance obj_game, that is a "Singleton" throughout the game and manages game state

I am trying to figure out what the best way to access its instance variables are

I have give them instance a name so i can reference or change GameManager.state (GameManager is the name of the instance).

Code:
GameManager.state = states.IDLE;
or is it better to run

Code:
with(obj_game) {
     state = states.IDLE
}
this is also a special case because there will only ever be one instance in the room, but would the same thing apply to having multiple instances and filtering out by the instance you want to modify?
 

Homunculus

Member
If you have only one instance the result is the same, but if it's just referencing variables, I prefer the first way since it's more concise. Obviously in the "with" case, by using the object name, you'd possibly be running that piece of code for all instances of the object. You can however target named instances directly using with, therefore
Code:
with(GameManager) {
    state = states.IDLE
}
is perfectly valid as well.

In the case of a singleton though, you could also just use

Code:
obj_game.state = states.IDLE
 

piranha305

Member
I am just curious if there are any advantages or disadvantage to the different approaches of using with or referencing the object directly like you mention

Code:
with(GameManager) { Property = x }
and

Code:
GameManager.PROPERTY = x
i get the second version of the code is more concise and readable, does wrapping the block with the with statement incur additional overhead? or is the dot notation just syntactic sugar and they just perform the internal logic?
 

Catastrophe

Member
I'm not sure if there's much of a difference if you're using the instance_id like that, but there is if you're using the object_index.

E.g.

with (obj_game) {stuff} will do nothing if there are no obj_name, but obj_game.stuff = thing will crash if there are none.

I wouldn't concern yourself if there's exactly one instance, in my game I just use whatever's convenient (with for complex, . for single line)
 

Homunculus

Member
I agree with @Catastrophe , there may be a difference in performance since with has to run in the context of the instance, but it's definitely negligible. If you are doing more than just setting a few variables, with is convenient precisely because of the above though, the code is run in the scope of the provided instance, giving you direct access to its variables.
 
Top