ga1pi2
ga1pi2

Reputation: 3

using string.find to find a string in a list (Lua)

i am making a script in lua for a game called "Stormworks" and i don't know how to search a list for a certain word

currently i am using this but it says that it doesn't work with lists

if string.find(message,Word_list)
then
server.announce("[Server]", "hey! "..sender_name.." watch your language")
end

Upvotes: 0

Views: 1321

Answers (1)

Personage
Personage

Reputation: 484

string.find does not take a table as an argument. Also, unless you are looking for a particular pattern within a string, there is no need to use string.find to check for string equality; use the == operator instead.

If you have a table that contains n number of strings and you are searching for a particular string—again, just simple equality—then iterate through the table and check each element.

-- Requires: tbl is a table containing strings; str is a string.
-- Effects : returns true if tbl contains str, false otherwise.
local function find_string_in(tbl, str)
    for _, element in ipairs(tbl) do
        if (element == str) then
            return true
        end
    end
    return false
end

local t = {"hello", "there", "friend"}
print(find_string_in(t, "friend"))
print(find_string_in(t, "goodbye"))

This produces the following output:

true
false

Upvotes: 1

Related Questions