Data Realms Fan Forums
http://45.55.195.193/

Short circuiting in Lua
http://45.55.195.193/viewtopic.php?f=73&t=19533
Page 1 of 1

Author:  Petethegoat [ Tue Aug 17, 2010 11:13 pm ]
Post subject:  Short circuiting in Lua

Hey all.
I have a script as follows:
Code:
for actor in MovableMan.Actors do
   if self.box:WithinBox(actor.Pos) == true then
      self.Health= 0
   else
      self.Health = 100
   end
end

How would I have the script end (for that frame) if the check is found true?

Edit:
I'm not 100% sure that short circuiting is the correct term.
Please inform me if it isn't.

Author:  TheLastBanana [ Tue Aug 17, 2010 11:52 pm ]
Post subject:  Re: Short circuiting in Lua

You're looking for the term "break".
Code:
for actor in MovableMan.Actors do
   if self.box:WithinBox(actor.Pos) == true then
      self.Health= 0
      break;
   else
      self.Health = 100
   end
end

Author:  Petethegoat [ Wed Aug 18, 2010 12:15 am ]
Post subject:  Re: Short circuiting in Lua

I'm genuinely shocked that I didn't think of that, thanks!
Also, thanks for reminding me to semicolon properly.

Image

It now works when more than one actor exists, joyfully.

Author:  akblabla [ Thu Aug 19, 2010 3:15 pm ]
Post subject:  Re: Short circuiting in Lua

Don't know if it would work better or not, but i would just write the code like this

Code:
for actor in MovableMan.Actors do
   if self.box:WithinBox(actor.Pos) == true then
      self.Health= 0
   end
end


It is shorter and i think your previous code would make everyone's health stay at 100 when they are outside the area

Author:  TheLastBanana [ Thu Aug 19, 2010 7:18 pm ]
Post subject:  Re: Short circuiting in Lua

Actually, that is more efficient. However, to have the same effect as his code, don't forget to include this line first:
Code:
self.Health = 100;

Author:  Petethegoat [ Thu Aug 19, 2010 7:29 pm ]
Post subject:  Re: Short circuiting in Lua

Code:
function Create(self)
   self.box = Box(Vector(self.Pos.X - 85, self.Pos.Y - 65), Vector(self.Pos.X + 85, self.Pos.Y + 70));
end

function Update(self)
   self.Scale = 1;
   for actor in MovableMan.Actors do
      if self.box:WithinBox(actor.Pos) == true then
         self.Scale = 0.001;
      end
   end
end

Works perfectly.

The self.Health was just because I wasn't sure if I'd want to publicly demonstrate the actual purpose I had in mind.
As it happens, I'm not really bothered. It's an interesting effect, but of questionable usefulness.

Page 1 of 1 All times are UTC [ DST ]
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
http://www.phpbb.com/