Attempt to index nil when trying to add a value to a dictionary?

Hey there! I’m trying to use a module script to save dictionaries so I can easily access/save them, but for some reason I can’t save any data to it.

It does work if I do this:

-- example
inventoryData.Set(player.UserId, gear, {['upgradeNr'] = value})

But not like this:

-- example
equippedData.Set(player.UserId, itemType, item)

And I get the index nil error.

Modulescript:

local module, data = {}, {}

function module.Set(key, name, values)
	data[key][name] = values
end

function module.SetAll(key, values)
	data[key] = values
end

function module.Get(key)
	return data[key]
end

return module

Any way I can make this work? Any help is appreciated!

You need to declare the data[key] table first or else it won’t be able to index for ‘name’ in this case. Apply this for every sub-keys that you want to create.

function module.Set(key, name, values)
	if not data[key] then -- checks if data[key] doesn't exist then creates one
		data[key] = {} -- set it as a table so you can index them later with 'name'
	end
	
	data[key][name] = values
end

if you call module.Get(key), you should get the dictionary you wanted

1 Like

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