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

how do you find something in a table?

Asked by 8 years ago

I'm curios how do you find something in a table by typing in a string? It would look kinda' like this:

Table = ["cheese","pizza","coca-cola","DORITOS!!!","blox-e-cola"]
drink = Table[blox-e-cola]

2 answers

Log in to vote
2
Answered by 8 years ago

you would want to use the for method. By calling

for i=1, #tableName do

you are running through the contents of a table. Simply adding in the variable name you are looking for will allow you to pick out the correct variable from the table!

Here is your new code:

Table = {"cheese","pizza","coca-cola","DORITOS!!!","blox-e-cola"}
drink = nil

for i=1, #Table do
    if Table[i] == "blox-e-cola" then
        drink = Table[i]
    end
end
Ad
Log in to vote
2
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
8 years ago

Turtle is right, but there's another solution that's shorter if you're able to do it.

It makes use of dictionaries. Take a look:

local food = {cheese = true, pizza = true}

if food["cheese"] then
    print("found it!")
end

Basically, we made the keys what we wanted, in this case cheese and pizza. We then made those keys link to the value true. So food["cheese"] is equal to true, and it passes the if statement.

If we try to use a key that's not in the table, such as food["pickles"], it will return nil because that key doesn't have a value, therefore not passing the if statement.

Answer this question