If the issue persists and using pcall
doesn’t resolve the situation because the problem lies with the function call itself returning nil
or not behaving as expected, we need to adjust the approach to explicitly handle the possibility of nil
values or ensure that the operation inside the pcall
can successfully complete.
local bb = option.BuyButton
local function attemptPurchase()
local toServerFunction = Functions:WaitForChild("ToServer", 10) -- waits up to 10 seconds for the child
if not toServerFunction then
UpdateText(bb, "Server error. Please try again.", 2)
return
end
local result
local success, errorMessage = pcall(function()
result = toServerFunction:InvokeServer("PurchaseItem", tool.Name)
end)
if success and result then
if result == "Success" then
UpdateText(bb, "Purchase complete!", 2)
return true
elseif result == "Failure" then
UpdateText(bb, "Insufficient funds", 2)
else
UpdateText(bb, "Unexpected error: " .. result, 2)
end
else
UpdateText(bb, "Failed to communicate with server: " .. (errorMessage or "Unknown error"), 2)
end
return false
end
-- Attempt to make the purchase, retry once if it fails
if not attemptPurchase() then
wait(1) -- Wait for a second before retrying
attemptPurchase() -- Retry the purchase once
end