Code Issues - Remove Index from Table getting nil value

Hello! Something strange is happening in my code and I’ve been trying to solve it for days. Would someone be so kind as to give me a hand with this?

What’s happening is the following: I’m trying to remove the index from the orderData table and I think I’ve done everything correctly. I don’t see any errors in my code, but I’m getting the error output that you can see below, and when I click on it, it takes me to that part of the code. What’s wrong or how can I fix this? :pray::pray::pray:

local success, errorMessage = deliverOrderFunction:InvokeServer(orderData, index)

output error:

localscript code:

-- Connect the MouseButton1Click event for the deliveryOrderButton
deliveryOrderButton.MouseButton1Click:Connect(function()
	-- Handle the delivery order button click
	print("Delivery order button pressed")

	-- Obtain the name of the nearby user
	local nearbyCustomer = checkNearbyCustomer()
	if nearbyCustomer == "" then
		print("No nearby customer found.")
		return
	end

	-- Check if there is an order for the nearby user
	local orderExistsForCustomer = checkOrderExists(nearbyCustomer) 

	if orderExistsForCustomer then
		-- Get the order for the nearby user
		local orderData = nil
		local index = nil
		for i, order in ipairs(orders) do
			if order.username == nearbyCustomer then
				orderData = order
				index = i -- Store the index
				break
			end
		end

		if orderData then
			-- Print the order data before processing
			print("Order data before delivery:")
			for key, value in pairs(orderData) do
				print(key, value)
			end

			processOrder(orderData)

			-- Call deliverOrderFunction with orderData and index
			print("Calling deliverOrderFunction with orderData and index:", orderData, index)
			local success, errorMessage = deliverOrderFunction:InvokeServer(orderData, index)
			if success then
				print("Order delivery successful.")

				-- Update any UI or data related to the removed order here
				local OrderReceivedByCustomer_UI = game.Players.LocalPlayer.PlayerGui:WaitForChild("OrderReceivedByCustomer_UI")
				OrderReceivedByCustomer_UI.Enabled = true
				OrderReceivedByCustomer_UI.ReceivedByCustomer_TextLabel.Text = "Order Received by ".. nearbyCustomer ..". + $".. orderData.totalprice .." CB"
				wait(3)
				OrderReceivedByCustomer_UI.Enabled = false

				wait(.2)
				-- Remove the delivered order from orderData
				orderData = nil

				-- Remove the delivered order from orders table
				table.remove(orders, index)

				-- Print a message indicating successful removal
				print("Order successfully removed from orders table. Index:", index)
				print(orderData)
			else
				print("Failed to deliver order:", errorMessage)
			end
		else
			print("Failed to find order data for nearby customer:", nearbyCustomer)
		end
	else
		print("No order found for nearby customer:", nearbyCustomer)
	end
end)

server script:

-- Get the RemoteFunction for delivering orders from the client
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local deliverOrderFunction = ReplicatedStorage.remoteFunctions:WaitForChild("deliverOrderFunction")

local deliveryBoxesFolder = game.Workspace.Game_Elements.Deliverables.CheffDeliver_Area.deliverAreasBoxes

-- Function to find the nearest delivery areas to the player that do not have a tool cloned already
local function findNearestDeliveryAreas(player)
	local nearestAreas = {}
	local shortestDistances = {math.huge, math.huge} -- Initialize with large values

	-- Iterate through all children of deliveryBoxesFolder
	for _, area in pairs(deliveryBoxesFolder:GetChildren()) do
		if area:IsA("Part") then -- Check if the child is a Part
			local distance = (area.Position - player.Character.HumanoidRootPart.Position).magnitude
			if distance < shortestDistances[1] then
				-- Update the first nearest area
				shortestDistances[2] = shortestDistances[1]
				nearestAreas[2] = nearestAreas[1]

				shortestDistances[1] = distance
				nearestAreas[1] = area
			elseif distance < shortestDistances[2] then
				-- Update the second nearest area
				shortestDistances[2] = distance
				nearestAreas[2] = area
			end
		end
	end

	-- Check if there's already a tool cloned in each nearest area
	for i, area in ipairs(nearestAreas) do
		local tool = area:FindFirstChildOfClass("Tool")
		if tool then
			-- Remove the area from the list if there's already a tool cloned there
			table.remove(nearestAreas, i)
		end
	end

	return nearestAreas
end

-- Handle the server invocation
deliverOrderFunction.OnServerInvoke = function(player, orderData, index)
	-- Print order details
	print("Item 1: " .. orderData.item1)
	print("Item 2: " .. orderData.item2)
	print("Total Price: $" .. orderData.totalprice)

	-- Check if the player has any tools in their backpack
	local backpack = player.Backpack
	if not backpack or #backpack:GetChildren() == 0 then
		-- Player has no tools in their backpack, return false
		return false, "Player has no tools to deliver the order"
	end

	-- Get the player's tools
	local tools = {}
	for _, tool in pairs(backpack:GetChildren()) do
		if tool:IsA("Tool") then
			tools[tool.Name] = tool
		end
	end

	-- Print player's tools
	print("Player's tools:")
	for toolName, _ in pairs(tools) do
		print(toolName)
	end

	-- Check if the player's tools match the items in the order
	if tools[orderData.item1] then
		-- Player has item1
		local nearestArea = findNearestDeliveryAreas(player)
		if nearestArea then
			-- Clone item1 to the nearest delivery area
			local toolClone1 = tools[orderData.item1]:Clone()
			toolClone1.Parent = game.Workspace
			toolClone1:SetPrimaryPartCFrame(nearestArea.CFrame)
			toolClone1.PrimaryPart = toolClone1:FindFirstChild("PrimaryPart") or toolClone1.PrimaryPart

			-- Remove item1 from the player's Backpack
			tools[orderData.item1]:Destroy()
		else
			warn("Could not find a delivery area near the player.")
		end
	end

	if orderData.item2 ~= "" and tools[orderData.item2] then
		-- Player has item2 and it's not empty
		local nearestArea = findNearestDeliveryAreas(player)
		if nearestArea then
			-- Clone item2 to the nearest delivery area
			local toolClone2 = tools[orderData.item2]:Clone()
			toolClone2.Parent = game.Workspace
			toolClone2:SetPrimaryPartCFrame(nearestArea.CFrame)
			toolClone2.PrimaryPart = toolClone2:FindFirstChild("PrimaryPart") or toolClone2.PrimaryPart

			-- Remove item2 from the player's Backpack
			tools[orderData.item2]:Destroy()
		else
			warn("Could not find a delivery area near the player.")
		end
	end
	
	table.remove(orderData, index)

	return true, "Order successfully delivered"
end

Are you able to reply where it is erroring on the server side?
When a server script errors on an OnServerInvoke, this error is sent back to the client too. This is a server error.

You also have another issue which is unrelated to the error.
When you remove an element from the array and continue to loop. Everything is now shifted down by one.

You will need to keep count how many you have removed and do something like this

local Removed = 0

for i, area in ipairs(nearestAreas) do
		local tool = area:FindFirstChildOfClass("Tool")
		if tool then
			-- Remove the area from the list if there's already a tool cloned there
			table.remove(nearestAreas, i - Removed)
			Removed += 1
		end
	end
1 Like

Hello! Thank you so much for providing that help, but I noticed an unexpected error in my code! The issue is that I’m handling too many remote events in my single LocalScript, and what I had to do was to create a specific LocalScript for the delivery button with the updated orders table, and now it works perfectly fine. Thank you very much for your feedback.

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