Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Local Variable Changing to Nil between lines??

Asked by 3 years ago
Edited 3 years ago

I have this localscript that's supposed to: 1. Wait for the StringValue "Current" to change 2. Delete all the letters of the text box it's a child of one by one 3. Retype them 4. Wait until a change has been made

local Shop = script.Parent.Parent
local Bar = script.Parent
local Current = Shop.Current

while true do
    --local Text = Current.Value
    --local NewText = Text 
    if NewText == "" then
        local Text = "Select Item"
        local NewText = Text 
        print (NewText)
    end
    if Current.Value == "GFL" then
        NewText = "Golden Flashlight"
    end
    if Current.Value == "SPB" then
        NewText = "Sprint Boost"
    end
    if Current.Value == "SMA" then
        NewText = "Stamina Boost"
    end
    while Bar.Text == NewText do
        if Current.Value == "GFL" then
            NewText = "Golden Flashlight"
        end
        if Current.Value == "SPB" then
            NewText = "Sprint Boost"
        end
        if Current.Value == "SMA" then
            NewText = "Stamina Boost"
        end
        wait()
    end
    local times = Bar.Text:len()
    local Text = NewText
    for count = 1, times do
        Text = (string.match(Bar.Text, "$"))
        wait(0.05)
        Bar.Text = Text
    end
    if NewText ==  nil then
        local Text = "Select Item"
        local NewText = Text 
        print (NewText)
    end
    print(NewText)
    local times = NewText:len()
    --for i, letter in pairs(string.split(NewText,"")) do
--      Bar.Text = Bar.Text..""..letter
--      local Text = Text..""..letter
--      wait(0.05)
--  end
    wait()
end

I'm sure the answers obvious, but the output at line 44 reads as "Select Item," but line 46 reads Nil. Is there something affecting it between the two?? Please help Edit: The comment part at the bottom is the part that deletes the old text one by one

1 answer

Log in to vote
0
Answered by 3 years ago

I believe that your problem is how you are setting the variable. You are making a local variable inside of an if statement. This means that you can only use this variable inside of that statement. For example:

local a = 1

if a = 1 then
    local b = 2
end

print (b) --returns nil because b is set as a local value in the if statement.

To fix this, you instead define the variable here:

local a = 1
local b = nil

if a = 1 then
    b = 2
end

print(b) --returns 2

Hope this helped and let me know if you still don't quite understand why this happens.

Ad

Answer this question