Modifying a variable passed as an argument inside a function gets lost

Here’s my code:

What ends up getting printed:

image

The issue I’m having is, prevXposButtonText isn’t getting updated, because prevText is.
Even when I move the local prevXposButtonText = "" above the function, the issue persists. Any way to update prevXposButtonText instead of prevText, preferably without a numberValue? Thanks!

Lua/Luau doesn’t behave the way you may think for this; when you update the value of prevText here:

image

This only updates the value of the parameter within the function; it does not update the value of the former variable (prevXposButtonText) in memory. When you pass a variable into a function, it will pass the value of the variable instead of a reference to the variable (tables behave slightly differently). You would have to manually update the other variable separately.

Essentially, your code should be structured like this:

local prevXposButtonText = "" -- store the variable here
local function onlyAllowNumbersIntoTextBox(text)
    --... other code...
    prevXposButtonText = text -- update the variable outside the function from here
end
1 Like

Awesome explanation. Got it first try., (a rarity with the devforum)

The reason I made it into a function, is so I don’t have to write the same code over and over again:

sooo, is there a way I can do this? With a return prevText maybe? Thanks!

For this, I would keep the buttons and the values of the TextBoxes stored in a table:

local textboxes = {
    X = {
       Instance = <TextBox>,
       PreviousText = ""
    }
}

The format isn’t too repetitive (at least for me). This allows you to also keep any additional info you would like to have.

You would then loop over the table and connect to each TextBox when their text is updated:

for _, textBoxData in textboxes do
    textBoxData:GetPropertyChangedSignal("Text"):Connect(function()
         onAllowNumbersIntoTextBox(textBoxData)
    end)
end

Within the event connection, you would pass the textBoxData information into the onlyAllowNumbersIntoTextBox function, and update the PreviousText property from within it:

local function onlyAllowNumbersIntoTextBox(info)
    local text = info.Instance.Text -- the current text in the TextBox
    --... other code...
    info.PreviousText = text -- update the property in the table
end

And if you want to retrieve it elsewhere, you can just do this:

print(textboxes.X.PreviousText)

But this is just how I would do it; I don’t know if it’s compatible or would work with your system. But, if you want to use tables, you can try it

do you know why it’s giving me an error? Sorry for the delayed response.

You’re forgetting commas at the ends of each line

1 Like

right :man_facepalming:

Summary

30 chаracters

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.