is it safe to use variables not sent to func

Discuss any general programming issues here
Post Reply
Bugala
Posts: 1390
Joined: Sun Feb 14, 2010 7:11 pm

is it safe to use variables not sent to func

Post by Bugala »

I accidentally did some bad code today by not having sent necessary information to the Function, but used those variables from outside the function, and it worked.

here an example:

Code: Select all

Function myfunc()
	DebugPrint(n)
EndFunction

For n = 1 To 3
myfunc()
Next

Normally I would send that n as one of the arguments to "myfunc", but this time I didnt.

As I was wondering about this, this could actually be somewhat handy way to make code cleaner in some cases, like:

Code: Select all

for n = 1 to 100
DrawEnemy()
next
instead of:

Code: Select all

for n=1 to 100
DrawEnemy(Enemy[n].x, Enemy[n].y, Enemy[n].Weapon, Enemy[n].status,Enemy[n].whatevermore)
next
But is this a safe way to do this otherwise, except that n cant be Local, which in itself can cause problems?
SamuraiCrow
Posts: 475
Joined: Fri May 15, 2015 5:15 pm
Location: Waterville, Minnesota USA

Re: is it safe to use variables not sent to func

Post by SamuraiCrow »

The object oriented approach would be to replace DrawEnemy() with a draw() method contained in the enemy table structure. Then you could draw them using an iterator and making the [n] lookups into uses of the self variable in the method.

Code: Select all

Enemies={}
/* global acceleration */
global dx=3
global dy=4

Function createEnemy()
   local enemy={}
   enemy.x=0
   enemy.y=0
   ...
   return(enemy)
EndFunction

Function Enemy:draw()
   ...
EndFunction

Function Enemy:update()
   self.x=self.x+dx
   self.y=self.y+dy
   ...
   self:draw()
EndFunction

For k,v in IPairs(Enemies) Do v:update()
Or if you have a bunch of code written already, pass the table variable Enemy[n] in as a parameter and just do table lookups based on that.
I'm on registered MorphOS using FlowStudio.
Bugala
Posts: 1390
Joined: Sun Feb 14, 2010 7:11 pm

Re: is it safe to use variables not sent to func

Post by Bugala »

@SamuraiCrow

True, but wasn't looking at solution to that specific example, just giving generic example about what it could solve, although, indeed, it was a bad example since there is more obvious solution available, the one that you suggested.
Post Reply