Purpose of putting variables in functions? (Variable Scope lesson)

Hiya! I’m just trying to absorb this particular lesson, and I understand how scopes work now with variables and putting them out globally and the purpose of that. For curiosity’s sake; what’s the point of putting variables in functions? Would I be right to assume it’s so that the variable is only used in that particular function? Just trying to understand the purpose of that.

And I assume also that whilst every variable in the script could be global, too many would get messy if they’re not needed to be out globally?

Sorry if I’m not making sense here.

1 Like

absolutely spot on :slight_smile:

when declaring a variable inside a function, its scope is purely within that function and once that functions completed its no longer accessible outsside it.

yep, we can make alot of global variables. within projects that are small, its not such a big deal.
but, once projects get a little larger or dealing with larger ammounts of data these global variables take up memory space while the project is running.

its also a good idea to not use alot of global variables if its not needed for another reason.
when variables are global, then your entire project has access to them, which could mean that some other scene or script could change them and can lead to at least some annoying debugging, or something unwanted and break the game.

for the life of me, (having a brain not working moment) the only example of using variables within a function would be to swap the contents of two variables around.
there are other use cases, but heres an example

extends Node

var posX = 100
var posY = 50

func _ready():
	print("This is the values before swap : x = ", posX, " y = ", posY)
	swap_numbers(posX, posY)
	print("This is the values after swap : x = ", posX, " y = ", posY)

func swap_numbers(_x, _y):
	var tempvariable = _x
	_x = _y
	_y = tempvariable
	posX = _x
	posY = _y

not the best example sorry, but i hope it gives an idea

1 Like

Absolutely it does thank you!

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms