Page 1 of 1

Regarding variable names within a loop

Posted: Thu Jun 20, 2013 10:13 am
by andrew.207
Kind of hard to explain, so I'll paste a small bit of code.

Code: Select all

 
for i=1, #bloops do       -- Outer loop for iteration
  local ev = bloops[i]
  for j = 1, 4 do
    ev.velocity = ev.velocity * ev.decel
    ev.y1 = ev.y1 + ev.velocity*dt
    ev.x2 = ev.x2 + ev.velocity*dt
    ev.x3 = ev.x3 - ev.velocity*dt
    ev.y4 = ev.y4 - ev.velocity*dt
  end
end
etc etc. The issue is having to type the number each time. Perhaps there is something weird string concatonation like ev.y+j that works? I can't find any through searching.

If not, easy no answer to stop me searching and change the "object"'s construction to accomodate.

Cheers!

Re: Regarding variable names within a loop

Posted: Thu Jun 20, 2013 11:52 am
by micha
If the variables are just numbered, then it makes a lot of sense to use a table with numeric keys:

Code: Select all

ev.y[1] = ev.y[1] + ev.velocity*dt
As a rule of thumb: If you happen to write very similar code, multiple times, then this is a sign that you can simplify the code a lot.

Otherwise, if you have the name of a variable stored as a string, then you can access it with

Code: Select all

for i = 1,4 do
  name = 'y' .. i
  ev.[name] = stuff
end
The neat feature, here, is that you can use a string and sort of convert it to a variable name.

Re: Regarding variable names within a loop

Posted: Thu Jun 20, 2013 8:15 pm
by andrew.207
Exactly what I was looking for, cheers.

Re: Regarding variable names within a loop

Posted: Thu Jun 20, 2013 8:19 pm
by raidho36
That's really odd how he used array for entities but couldn't think of using it for coordinates.

Re: Regarding variable names within a loop

Posted: Tue Jun 25, 2013 12:31 am
by andrew.207
It's for gibbing. Basically it drawn each limb of the object with its own X Y and sends them apart based on what caused it. I kinda figured one "object" with a larger set of coordinates was better than mutliple objects becuase memory.

Re: Regarding variable names within a loop

Posted: Tue Jun 25, 2013 6:30 am
by Plu
You should generally not worry about memory and performance unless you're actually seeing it drag down, and even then only look for the worst offenders. You're most likely working on a machine with at least 1 gigabyte of memory, worrying over bytes of extra memory being used. You have close to a billion of them. You can afford to be a bit wasteful if it makes your code cleaner and more readable.