Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

[Sugarcube] Using one number to store multiple variables.

edited October 2016 in Help! with 2.0
Hy, I'm not quite sure how to put this.

I'd like to use one number(for example 1000) to store multiple variables by variables by modifying and reading individuals digits. For example if the character does one action the number changes to 1001, while another changes it to 1010. Then by reading the 3rd and 4th digits I can tell what action was done.

I'd like to do this to avoid variable explosion by keeping a lot of thematic related information in one space. I can make do currently making extensive use of divide by 10 and modulus by 10, but considering Sugarcube already has a "split" function, I was wondering if it would also have a "get character at position x" function.

The one way I though to do this without a special function is creating special "math" passages, where I use a hidden <<display>>function inside a passage to call up the formula needed to access a specific digit in a variable. Is this the only way?

Thanks for any help. :)

edit:typo fixing

Comments

  • You can do something similar to what you want by changing the values data-type from number to String and the using a combination of the Javascript String charAt method and the String substr method to handle the manipulation of the individual character that make up the String value.
    <<set $value to "1000">>\
    value: $value, last char: <<print $value.charAt(3)>>
    
    ''Replace the last char (index = 3) with a 1''
    <<set $value to $value.substr(0, 3) + '1' + $value.substr(3 + 1)>>\
    value: $value
    
  • When this comes up, I generally say don't worry about it or to simply use a generic object with a few properties. If you're bound and determined to do pack multiple states into one value, however, then, as an alternative to stupid string tricks, you might want to look into integer bitmasks.
  • Say your integer is 110110 and you want to test whether the third-to-last digit is a 1 or not. You could do
    <<set $testInt to 110110>>
    <<if $testInt % 1000 >= 100>>
    AWW YISSS!
    <</if>>
    

    You're essentially throwing out factors of 1000 and testing whether the rest begins with a 1.
  • Thank you everyone. Especially greyelf at mentioning the ability to use JavaScript methods.

Sign In or Register to comment.