Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Remove a value from a dictionary?

So lets say I have a dictionary,

local dict = {
	["hello"]	= 123,
	["world"]	= 456
}	

and now I want to use table.remove() to remove hello from the dictionary. Problem is table.remove() only takes a number for the second parameter (index of which to remove).

How would I go about doing this?

Here's a function I've made, but it's complete crap.

function GetIndexFromDictionary(tbl, str)
	local n = 0
	for i,v in next, tbl do
		print(i)
		n = n + 1
		return i == str and n
	end
end

1 comment

1

In addition to SatireIncarnate's answer, I'd like to point out that table.remove only works on arrays, since the second argument it requires is the numeric key it's searching the table for.

1 answer

✓ Accepted answer

Set it to nil

If something is nil, it simply doesn't exist.

t[k] = nil;

would clear the key k of table t

11 comments

0

what happens to t[k+1], is it still there?

0

Obviously because you set t[k] = nil, not t[k + 1].

0

the problem with that code is it simply erases both key and value,which is bad because they you dont have a base table to work with.

0

The only problem with this is nothing.

0

well then you should know making something nil is often bad when dealing with datastores, which dictionries after often used for in roblox, because there is no other reason to use them besides the case.

0

You really are an incredibly silly child. You have my pity.

0

mate i am probably the same age as you, you have my pity, because i doubt you understand tables.

0

You have even more pity

0

hi

0

Let's clear up some confusion: 1) It's absolutely necessary to set table entries to nil if you're working with session tables (caching) otherwise you'll get memory leaks. 2) Erasing the key and value is what you want, why have an empty key? 3) You can set a key and value at the same time (pretend k never existed in the table beforehand): t[k] = 1 this sets the key AND the value inside t table.

0
  1. There are plenty of other reasons to use dictionaries other than for datastores. Caching is a big one, but it can also be used to dramatically lower the amount of if statements you have (use passed variables instead of comparing every possible variation of a value in if statements).

This discussion is preserved as it was. New answers, comments, and votes are closed.