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

What is the best method of getting specific lines in a string ?

Asked by 5 years ago

For example,

local a = "Hello and good day to you!"

local b = "Hi there and good day to you too!"

(some form of detection)

Line 5 from string a = "to"

Line 2 from string b = "there"

I would love someone to answer how to detect the specific words!

0
string.find() DeceptiveCaster 3761 — 5y

2 answers

Log in to vote
1
Answered by
1waffle1 2908 Trusted Badge of Merit Moderation Voter Community Moderator
5 years ago

You can use string.gmatch to iterate over the words in the string.

local function GetWord(str, n)
    local count = 0
    for word in str:gmatch("%w+") do
        count = count + 1
        if count == n then
            return word
        end
    end
end

%w+ will capture runs of alphanumeric characters, which are the "words" being counted. GetWord returns the nth "word" in str.

0
orrrrrrrrrrr string.find() DeceptiveCaster 3761 — 5y
0
I think you interpreted the question entirely differently, your answer is not an alternative to mine. 1waffle1 2908 — 5y
0
1wafflel, thanks! ffastspeed5 12 — 5y
Ad
Log in to vote
0
Answered by 5 years ago

This is very simple, just use string.find():

local string = "Hello World!"
local s_find = string.find(string, "Hello")

The found part of the string can be used for whatever is needed with the string.

0
But I'm on about locating specific parts of the string, not specific words. ffastspeed5 12 — 5y
0
Let me rephrase, I'm on about a function to locate specific words based on lines of the string such as "string.find(string, 2) won't fine "World! will it? ffastspeed5 12 — 5y

Answer this question