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..
1 | --This code throws an error because it probably doesn't make any sense |
2 | x = { "first" , "second" , "thrid" } |
3 | print (string.find(table.concat(x, "third" ))) |
4 | --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.
1 | local x = { |
2 | first = 1 , |
3 | second = 2 , |
4 | third = 3 |
5 | } |
6 | print (x.second) -->2 |
Or, equivalently;
1 | local x = { |
2 | [ "first" ] = 1 , |
3 | [ "second" ] = 2 , |
4 | [ "third" ] = 3 |
5 | } |
6 | 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.
1 | x = { "first" , "second" , "third" } |
2 | print (string.find(table.concat(x, ", " ), "third" )) |
I would break up that line a bit so I could read the script clearly.
1 | x = { "first" , "second" , "third" } |
2 | concat = table.concat(x) |
3 | find = string.find(concat, "third" ) |
4 | 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.
1 | x = { "first" , "second" , "third" } |
2 |
3 | for i, v in pairs (x) do --Look through "x" |
4 | if i = = 3 then --If we're on the third index |
5 | print (v) --Print the third index |
6 | end |
7 | end |