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

How do you find the position of a certain value in a table?

Asked by 8 years ago

I've been searching and searching and it's only led me to what's probably the completely wrong answer. All that I've came up with in my search would be something like this..

--This code throws an error because it probably doesn't make any sense
x = {"first", "second", "thrid"}
print(string.find(table.concat(x, "third")))
--print(string.find(table.co:2: bad argument #2 to 'find' (string expected, got no value)

What I'm trying to print with the above code is "3", with the logic that "third" is the third value in the table.

2 answers

Log in to vote
0
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
8 years ago

Your trying to find the key from a value, but this isn't how tables work. The key is used to find the value, not the other way around.

However we can accomplish what I believe you want pretty easily with a dictionary. All we need to do is make the key be the string, and make the value be the number. This means we can take a string and find what number its value is.

local x = {
    first = 1,
    second = 2,
    third = 3
}
print(x.second) -->2

Or, equivalently;

local x = {
    ["first"] = 1,
    ["second"] = 2,
    ["third"] = 3
}
print(x["second"]) -->2
0
Qq, can metatables be assigned to dictionaries? I know that they're also tables so I dont see why not, but just checking. Also, thank you for pointing out this obvious answer to me. magiccube3 115 — 8y
0
I've never tried it but I don't see why you wouldn't be able to. Perci1 4988 — 8y
Ad
Log in to vote
0
Answered by
funyun 958 Moderation Voter
8 years ago

Check line 3. The error tells you that string.find needs a second argument. You put "third" in the wrong place.

x = {"first", "second", "third"}
print(string.find(table.concat(x, ", "), "third"))

I would break up that line a bit so I could read the script clearly.

x = {"first", "second", "third"}
concat = table.concat(x)
find = string.find(concat, "third")
print(find)

However, I'm assuming that this won't give you what you want. "first" is 5 characters long, "second" is 6, and "third" is 5. What you want is the position of "third" in the table. So, let's try a different approach. We'll use a generic for loop.

x = {"first", "second", "third"}

for i, v in pairs(x) do --Look through "x"
    if i == 3 then --If we're on the third index
        print(v) --Print the third index
    end
end
0
Oh thanks, I did not understand the error at all. However, the final solution you posted doesn't fit what you're saying/ what I need. I want to find the position in the table of a certain string. The above looks for the third instance in the table and then prints it. :L magiccube3 115 — 8y

Answer this question