• Our software update is now concluded. You will need to reset your password to log in. In order to do this, you will have to click "Log in" in the top right corner and then "Forgot your password?".
  • Welcome to PokéCommunity! Register now and join one of the best fan communities on the 'net to talk Pokémon and more! We are not affiliated with The Pokémon Company or Nintendo.

What happens in def getAutoDims (about how variables work in ruby)

Status
Not open for further replies.
119
Posts
10
Years
    • Seen Sep 1, 2023
    I'm trying to add message tags into the text of a command window, yet want to remove this in calculating the window's width. The width is calculated in 'resizeToFit' using 'getAutoDims', thus before calling 'getAutoDims' I remove the unwanted tags.

    Now the problem, and strange thing, is as follows; somehow the commands are set in 'getTextForDims'. Whatever I do, it always shows the commands send to that def, and even stranger if I store the old commands in a local variable that local variable is suddenly also overwritten with the new commands. There's nothing inside 'getAutoDims' which sets commands, but even then it also sets the local variable ('actualCommands' in the code below) which shouldn't even be possible.

    The code changes I made: (however 'getAutoDims(commands,dims,width)' is unchanged, only the other code in the 'Changed Lines' section)
    Code:
      def resizeToFit(commands,width=nil)
        dims=[]
    # CHANGED LINES ############################################################
        actualCommands = commands
        for i in 0...commands.length
          commands[i] = getTextForDims(commands[i]) [COLOR="Red"] # Just a text.gsub! removing the tags[/COLOR]
        end
        getAutoDims(commands,dims,width)    [COLOR="red"]# Problem always occurs after this line[/COLOR]
        commands = actualCommands   [COLOR="red"]# actualCommands isn't used anywhere else, yet has still changed[/COLOR]
    # END CHANGED LINES ############################################################
        self.width=dims[0]
        self.height=dims[1]
      end

    What causes this behaviour (and how is this even remotely possible)?
    (I know different ways to circumvent this problem, but those are dirty hacks which make the code a lot less flexible)
     
    Last edited:
    119
    Posts
    10
    Years
    • Seen Sep 1, 2023
    Apparently I misunderstood how variables work, and how they are passed, in ruby. The answer is that both variables point towards the same object, thus when the object is changed via one variable the other variable also shows this change.

    For a more detailed explanation see this post on stackoverflow: https://stackoverflow.com/questions/1872110/is-ruby-pass-by-reference-or-by-value

    (thread can be closed, posted this in case someone else encountered a similar problem)
     
    Status
    Not open for further replies.
    Back
    Top