This is a simple inventory system I made which caches players inventories and includes other inventory functions. The inventory is simple and only made to store items and not interactive items such as swords/armours etc. What I want to know is: Is my code efficient? Is there a better way of doing this? Are there any large holes which exploiters could take advantage of? The module script will be stored inside server script service and the player will only have access to the fetch_inventory function which will be done via remote function.
local inventory_module = {}
local inventory_cache = {}
inventory_module.set_inventory = function(player : Player, saved_inventory : any)
local name = player.Name
if saved_inventory ~= nil then
inventory_cache[name] = saved_inventory
print(string.format("loaded in %s's inventory",name))
else
inventory_cache[name] = {}
print(string.format("created inventory for %s",name))
end
end
inventory_module.fetch_inventory = function(player : Player)
if inventory_cache[player.Name] ~= nil then
print(string.format("returning %s's inventory",player.Name))
return inventory_cache[player.Name]
end
end
inventory_module.add_item = function(player : Player, item : string, amount : number)
if inventory_cache[player.Name] ~= nil then
if inventory_cache[player.Name][item] ~= nil then
inventory_cache[player.Name][item] += amount
else
inventory_cache[player.Name][item] = amount
print(string.format("adding %i %s to %s's inventory",amount,item,player.Name))
end
end
end
inventory_module.remove_item = function(player : Player, item : string, amount : any)
if inventory_cache[player.Name] ~= nil then
for i,v in pairs(inventory_cache[player.Name]) do
if i == item then
if amount == "all" then
inventory_cache[player.Name][item] = nil
print(string.format("removing all %ss from %s's inventory",item,player.Name))
else
inventory_cache[player.Name][item] = inventory_cache[player.Name][item] - amount
print(string.format("removing %i items %s from %s's inventory",amount,item,player.Name))
if inventory_cache[player.Name][item] == 0 then
inventory_cache[player.Name][item] = nil
print(string.format("item %s ran out from %s's inventory",item,player.Name))
end
end
break
end
end
end
end
inventory_module.terminate_inventory = function(player : Player)
if inventory_cache[player.Name] ~= nil then
inventory_cache[player.Name] = nil
print(string.format("removing %s inventory from cache",player.Name))
end
end
inventory_module.visualise_inventory = function(player : Player) -- for debugging reasons
if inventory_cache[player.Name] ~= nil then
print(string.format("visualising %s's inventory",player.Name))
for i,v in pairs(inventory_cache[player.Name]) do
print(string.format("%s : %i",i,v))
end
end
end
--[[
inventory_cache = { -- just so I can visualise the dictionary
tay_z3r = {
block = 5,
redblock = 6,
blueblock = 2
}
}
]]
return inventory_module