How do i insert a value into a table in Datastore2?

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve?

I want to insert table and saves them in datastore2. Like an inventory system.

  1. What is the issue?

I dont know how to insert table into datastore2.

  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?

Yes, i looked for some solution but nothing works for me.

This is my testing script/ i test Datastore2 stuff in here. Because i am very new to Datastore2


local players = game:GetService("Players")
local replicatedStorage = game:GetService("ReplicatedStorage")
local serverscriptservice = game:GetService("ServerScriptService")

local DataStore2 = require(serverscriptservice.MainModule)

local defaultCurrencyAmount = 10
local defaultTable = {10,23} -- default table

players.PlayerAdded:Connect(function(plr)
	local currencyStore = DataStore2("currencyStore", plr)
	local tableStore = DataStore2("tableStore", plr) -- table store
	
	local function updateCurrency(amount)
		replicatedStorage.RemoteEvents.UpdatePlayerCurrency:FireClient(plr, amount)
	end
	
	local function updateContent(contents)
		replicatedStorage.RemoteEvents.UpdatePlayerContent:FireClient(plr, contents)
	end
	
	updateCurrency(currencyStore:Get(defaultCurrencyAmount))
	updateContent(tableStore:GetTable(defaultTable))
	
	currencyStore:OnUpdate(updateCurrency)

	
	while wait(5) do
		currencyStore:Increment(3)
		-- here i want to add random numbers to the table every 5 second perhaps table.Insert()?
	end
end)

Thank you for reading my post, have a nice day :smiley:

1 Like

You can use table.insert(table, value) and pcall function wrap the tableStore:Set(table) method to save that data table.

2 Likes

like this?

while wait(1) do
		currencyStore:Increment(3)
		pcall(function(contentToAdd)
			table.insert(tableStore:Set(defaultTable, math.random(1,99)))
		end)
	end

it doesn’t work for me

2 Likes