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.
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
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