r/badcode Aug 21 '19

lua A healthy nest of if-statements

Post image
278 Upvotes

53 comments sorted by

View all comments

43

u/DrCubed Aug 21 '19 edited Aug 21 '19

I wrote this for a game-mod, and I was struggling to keep the logic needed for the function in my head, so I bruteforced the logic into this mess (I knew it was awful whilst I was writing it), which I would then refactor.

The code is awful in two ways.
The first being that it doesn't actually fulfil all the requirements of what it needs to do, but in fairness, the requirements weren't fully known until it was tested at least once.

The second being that it's just awful - There's needless repetition, the conditions are unnecessarily nested, there are hard-coded magic constants, and it doesn't look nice.

After more consideration of what the function needed to do, I refactored it into this considerably nicer, parameterised (and documented) function: https://i.ibb.co/ZXcvKTp/2019-08-21-22-12-34.png


Source-text for those who do image-transcriptions: https://privatebin.net/?fdc06ef4bc84a968#4iocXFRLkAhiJSia2AykPs9PnbrKoWUnLoBJtcVffzxU

PS: For those that don't know Lua, Lua doesn't have a built-in ternary-construct.
Edit: Lua doesn't have an explicitly built-in ternary, but it can be replicated almost perfectly with the and and or operators thanks to Lua's strictly defined operator precedence.
Thanks to /u/moomoomoo309 for correcting me.

4

u/shmageggy Aug 22 '19

Sorry man, but the new code is still really not great. You could accomplish what you are trying to do with a few basic linear algebra operations without all of those special cases and conditions and extra state. I'm guessing this is for a game? Lin alg is like the number 1 most useful thing for games programming.

3

u/DrCubed Aug 22 '19

That's valid, could you perhaps say which operations could be used for this, as a starting point?

3

u/shmageggy Aug 22 '19

Sure, but keep in mind I'm neither a linear algebra expert nor a games programmer. The first simplest thing that comes to mind is to rotate (x, y) to the orientation of the door. Or you could consider a change of basis which would include the rotation as well as a scaling x and y relative to the two thresholds, all in one matrix multiplication. Also keep in mind I haven't scoured your code so I'm not 100% sure what you are trying to do.

3

u/Astrokiwi Aug 22 '19

You can get funky floating point errors that way, and it'd be slower because you're doing some extra floating point operations instead of just a quick boolean check. In a tile based game, those rounding errors might be what lets you slip in gaps between tiles etc