The Crystal Programming Language Forum

Trouble with recursive variables?

I’m having trouble getting the math in my app to work properly, it’ll work in the moment, but it doesn’t seem to keep it, it just immediately resets back to what it was set to previously
Only been using Crystal for a few days, so it could be something obvious

https://play.crystal-lang.org/#/r/7531

Hi, that’s a lot of code

Please reduce and show an example of specific code and why it’s not working the way you want

Will help lead devs and other devs isolate the issue and give you help faster

I would maybe take a more OOP approach to this. There is a lot of duplication that could be removed. I haven’t thought it all out yet, I’ll see if i can come up with an example later today.

@Jack-Chronicle Check this out. (And @girng you should look at this too :P)

https://play.crystal-lang.org/#/r/75ei

Refactored it to be more OOP. A lot of code is now able to be reused to keep things DRY. I.e. dont need detail methods for each attribute, dont need big if/else blocks for improve/weaken.

I didn’t get too far into it. There is still some funky stuff you can play with. Mostly around clearing lines and stuff. This also doesn’t do any validation that you give it a valid number. But it shouldn’t be too hard to do that. Maybe just to .to_i? and if it returns nil it’s invalid?

I hope this gives you a better idea of some better practices that will make developing it easier as well as increase maintainability.

1 Like

Blacksmoke just coded his game LOL

Yeah OOP looks much nicer

@Jack-Chronicle the problem with the math is that for example, the def improve is changing the value of arguments, which are passed by value. The changes applied to them are not persisted in the outer most state.

You will need to have some other kind of global state or pass the context.

Whether you prefer to code in a procedural, oop or more functional manner is totally up to you :-)

wow, yeah… that looks a lot nicer. And runs much better
Hadn’t even thought of doing it that way, and some of this code is new to me. I’ll definitely be doing more research into this to figure out how all of this works
Been a huge help, thanks. Basically coded the entire first stage yourself, or at least optimized it all… I’ll give you credit in it, since you’ve basically done all of it. Unless you don’t want any XD

1 Like

Haha thanks. But naw, just take it as a learning experience :stuck_out_tongue: