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

How to get "cow" out of a table and print it?

For example,

local dictionary = {["cow"] = 1, ["sheep"] = 1}
local random = dictionary[math.random(1, #dictionary)]
print(random) --This would print 1

but how do I get the name of where the 1 came from?

local dictionary = {["cow"] = 1, ["sheep"] = 1}
local random = dictionary[math.random(1, #dictionary)]
print(????) --This would print where the 1 came from

1 comment

0

When you fix this, you should add "math.randomseed(os.time())" in the beginning so you don't always get "cow" or "sheep" at every run.

2 answers

✓ Accepted answer

What you can do is loop through the table, and check for the value of the key, then you will be able to print the key.

Something like this:

local table1 = {}
table1["cow"] = 1

for i, v in pairs(table1) do
	if v == 1 then
		print(i)
	end
end

Hope I helped, if you have any further questions please let me know.

2 comments

0

This helps a lot! Thank you. However, what if I specifically wanted it to print out 1, but also the key. Like if I chose a random one.

0

In that case, one thing I would do is do table1 = {cow = {Value = 1, Key = "cow"}} and then choose a random one out of the table, then print(randomChoice.Key)

The correct name of this post should be : How to get "cow" out of a table and print it?. But its fine. Here you go!

local table = {}
table["cow"] = "Cow"
print(table["cow"])

It seems you had it backwards. Using table["Cow"] = 1 will be like this in the table ["Cow"] = {1}

2 comments

0

Sorry, I think I made my question too vague. I will make a better example, give me a minute.

0

Alright, I have fixed my question.

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