How to insert a value into a dictionary?

so i have been making a modulescript allowing u to create a private server using reserveserver however i want to assign it to another code thats shorter i did that but it says attempt to index nil with “code” so how do i insert the values like this

local table = {
[“qwewqrq”] = “private server key”
}
etc
and here is the code

local module = {}
local TS = game:GetService("TeleportService")
local DTS = game:GetService("DataStoreService")
local CodesDatastore = DTS:GetDataStore("CodesDatastore")
local alphabet = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"}
local codetable = CodesDatastore:GetAsync("Codes")

function module:CreatePrivateServer(placeid)
	local id
	local succes, err = pcall(function()
		id = TS:ReserveServer(placeid or game.PlaceId)
	end)
	if succes then
		local code = ''
		for i = 5,1,-1 do
			local letter = alphabet[math.random(1,#alphabet)]
			code = code..letter
		end
		codetable[code] = tostring(id)
		local codeid = codetable[code]
		print(codetable)
		CodesDatastore:SetAsync("Codes",codetable)
		
	else
		print(err)
	end
	
end


function module:GetCodes()
	return codetable
end

return module

1 Like

Perhaps it’s better to do this? Since data can be nil

local codetable = CodesDatastore:GetAsync("Codes") or {}

i actually had that before i will put it back and see if the error goes away

still however this time it is at line 19 saying attempt to index nil with “ydbef” the codes are randomly generated tho

try to print the table codetable before running.

	if succes then
		print(codetable)
		local code = ''
		...

it will still be empty as i assign the code to the id at line 21 but ok

it now has no errors and says table = 0x02131 or some long code however it should be
table = [“qweasr”] = 0x02131

can you send a screenshot/table?

yes im gonna do that wait please

it means everything works for you, because in the game the table looks like this when printed. You can also print the table with a loop (if you want).

for i, v in pairs(codetable) do
	print(i, v)
end

but why cant i see the key and the value? i only see the value

if i print it in the loop it doesnt print anything

Are you sure? try this code to see what’s wrong.

codetable[code] = tostring(id)
print(code)
local codeid = codetable[code]
print(codeid)
for i, v in pairs(codetable) do
	print(i, v)
end

it works now all of a sudden ig it was just an error in the datastore

i marked it as solution thanks man!

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