Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 4 years ago
Edited 4 years ago

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
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. xMicro_Canary 37 — 4y

2 answers

Log in to vote
1
Answered by
Nanomatics 1160 Moderation Voter
4 years ago

What you can do is loop through the table, and check for the value of the key, then you will be able to printthe 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.

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. Brandon1881 721 — 4y
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) Nanomatics 1160 — 4y
Ad
Log in to vote
0
Answered by
Lakodex 711 Moderation Voter
4 years ago
Edited 4 years ago

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}

0
Sorry, I think I made my question too vague. I will make a better example, give me a minute. Brandon1881 721 — 4y
0
Alright, I have fixed my question. Brandon1881 721 — 4y

Answer this question