Two scripting related tipps:
The first one is a general rule: Comment your own code! Not necessarily for others, but also for yourself, because after a coffee-powered night of half-awake scripting, on the next day it's reasonable to assume that you won't know anymore what you did and why you did it. So generally it's always a good idea to comment your code so not only yourself but also another person could understand it, cause very soon you will be this person
The second is on how to generally design your scripts. In scripting there are not many methods for abstraction, so sooner or later you'll end up with spaghetti code. It will be hard to follow control flow, and optimization becomes more and more difficult. One way I sometimes handle this is by designing my scripts based on discrete finite machines (if they're called like this in english). I'll give a simple example to illustrate the concept:
1. Abstract Features:You want to create a script for an armor that provides a stealth field effect. This stealth field can be switched on and off by a hotkey. Additionally, it will consume energy cells when active.
Next, find discrete states for your script. There are many possbilities, so you'll have to think a little (and eventually change then later). One example:
2. Discrete states:0: Stealth field disabled (can't be switched on)1: Stealth field standby2: Stealth field enabled
You could also have only 2 states (on/off), or more (disabled, enabling, enabled, activating, activated, disabling). But those 3 seem about right. Next, you have to create transitions from one state to another. These are based on conditions.
3. Conditions:cEquipped - Armor is equippedcHotkeyPressed - Stealth toggle button is pressedcEnoughCells - Enough energy cells left
For complex states/transitions, you can also draw a small graph.
4. Transitions between states0->0: !cEquipped0->1: cEquipped1->0: !cEquipped1->1: cEquipped && (!cHotkeyPressed || !cEnoughCells)1->2: cEquipped && cHotkeyPressed && cEnoughCells2->0: !cEquipped2->1: cEquipped && (cHotkeyPressed || !cEnoughCells)2->2: cEquipped && !cHotkeyPressed && cEnoughCells
These can be optimized later in the code. Speaking of which:
if state == 0 // do stuff // Evaluate transitions if cEquipped == 1 set state to 1 return endif return elseif state == 1 // do stuff // Evaluate transitions if cEquipped == 0 set state to 0 return elseif cHotkeyPressed == 1 && cEnoughCells == 1 set state to 2 return endif returnelseif state == 2 // do stuff // Evaluate transitions if cEquipped == 0 set state to 0 return elseif cHotkeyPressed == 1 || cEnoughCells == 0 set state to 1 return endif returnendif
(Hopefully I didnt make too many logical mistakes)
While for small stuff this may be overkill, for larger scripts this generally results in a clear structure. I say it's easy to debug, understand and already well optimized because only a single state's code will run per script execution.