'How can I get the text value of a button in Roblox Lua

How can I add the text value of clicked button to display. Currently, only first button functions and prints nicely.

local Key = Instance.new("Part");
local DisplayVal =""

Key = workspace.KeyPads.Keypad1.SurfaceGui.keys;
Key.MouseButton1Click:connect(function(hit)
    
    DisplayVal = DisplayVal .. Key.Text
    workspace.KeyPads.Keypad1.SurfaceGui.display.Text = DisplayVal
end)


Solution 1:[1]

I'm assuming that you have this code copied inside each button on the keypad.

That means that each button is using their own version of DisplayVal. When you hit one button, that button's DisplayVal gets set. If you hit the same button again, I'm sure it would work properly, but as soon as you switch to a different button it would revert back to the empty string.

So to fix this, why not just use the text from the display directly, rather than holding onto a variable version?

local Gui = workspace.KeyPads.Keypad1.SurfaceGui
local Display = Gui.display
local Key = Gui.keys

Key.MouseButton1Click:Connect(function()
    local DisplayText = Display.Text .. Key.Text
    Display.Text = DisplayText
end)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kylaaa