I have a table that contains some strings. I just want to find an element by just an index. Like table.findbyindex(StringTable,math.random(1,#StringTable)) (This isn’t a real code)
local t = {"a", "b", "c"}
print(t[math.random(1, #t)])
Oh! Thank you. I didn’t know this was that simple.![]()
No problem! And yes. Arrays are ordered lists and indices are usually implicit except when they’re written like so:
local letters = {
[1] = "a",
[2] = "b",
[3] = "c",
}
Similarly to dictionaries where we have keys, letters[index] fetches a value stored to that index.
table.find(), on the other hand, checks every string from the start of the list onwards until it finds it and returns the index, so in the most basic sense it is a much faster version of:
local function StringFind(tbl, str)
for index, value in letters do
if str == value then
return index
end
end
end
print(table.find(letters, "c")) --> 3
print(StringFind(letters, "c")) --> 3