Opinion on my server-synced fruit stock

(This is just a practice, I want to know if this is ok. Feel free to comment and give advice)

-- I'm going to randomize 1 fruit, not based on rarity.

local part = script.Parent
local BillboardGui = part.BillboardGui
local TextLabel = BillboardGui.TextLabel

local MessagingService = game:GetService("MessagingService")
local DataStoreService = game:GetService("DataStoreService")
local data = DataStoreService:GetDataStore("Stock")

local restock_min = 5
local total_min = ((restock_min or 10)*60)

local fruit_list = {
	"Apple",
	"Banana",
	"Grape",
	"DragonFruit",
	"Peach",
	"Corn",
	"Tomato",
	"Lime",
	"Lemon",
}

MessagingService:SubscribeAsync("ResetStock",function(currentFruit)
	print(currentFruit)
	TextLabel.Text = currentFruit.Data
	data:SetAsync("Stock",currentFruit.Data)
end)
-- update stock after player joins in an empty server
MessagingService:PublishAsync("ResetStock",(data:GetAsync("Stock") or fruit_list[math.random(1,#fruit_list)]))
while true do
	local timeleft = total_min-os.time()%total_min
	--print(total_min-os.time()%total_min)
	
	if timeleft<=1 then
		local nextFruit = fruit_list[math.random(1,#fruit_list)]
		MessagingService:PublishAsync("ResetStock",nextFruit)
	end
	task.wait(1)
end

It’s decent overall, one suggestion; wrap the DataStore SetAsync in a pcall in-case of server issues, roblox outages, throttling, etc.

1 Like