简体   繁体   中英

Lua how to split a word pair string into two separate variables?

I have this code which reads a txt file which contains simply a list of word pairs on each line separate by a space and for every line, the code will split the word pair into separate word and print each word one after the other:

file = io.open( "test.txt", "r" )

temp = {}
for line in file:lines() do
    for word in line:gmatch("%w+") do
        print(word)
    end
end
file:close()

sample test.txt

big small
tall short
up down
left right

output

big
small
tall
short
up
down
left
right

However, I find myself needing to split each word in each word pair into separate variables such that I can use an if statement on word1 in order to do something with word2.

Something like:

file = io.open( "test.txt", "r" )

temp = {}
for line in file:lines() do
    for word in line:gmatch("%w+") do
        word1 = first word
        word2 = second word
        if (word1 = "tall") then
            print(word2)
        end
    end
end
file:close()

I don't program in Lua myself so apologies beforehand if there's something wrong with the following code

file = io.open( "test.txt", "r" )

temp = {}
for line in file:lines() do
        words = {}
        for word in line:gmatch("%w+") do table.insert(words, word) end
        if (words[1] == "tall") then
                print(words[2])
        end
end
file:close()

Running this against the test file you gave returns the word short and I assume this is what you needed?

For a few words you can use captures. This mechanism allows to get specific parts of a match.

See https://www.lua.org/manual/5.4/manual.html#6.4.1

local w1, w2 = line:match("(%w+)%s+(%w+)")

Alternatively, especially for many words you'd put all words into a table.

local line_words = {}
for word in line:gmatch("%w+") do
  table.insert(line_words, word)
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM