HobbitOfShire
HobbitOfShire

Reputation: 2414

How to split string into two arrays in Lua?

I am using Lua and i have a file that i want to split each line into two different arrays. Each line of my file contains two string seperated with a space. for example if my file contains

 something something_else

I should have

tab_1[1] = something
tab_2[1] = something_else

I tried using split like

file =io.open("myfile.txt", "r")
for line in file:lines() do
line = file:read()
for value in split(line," ")
table.insert(tab_1,value[i])
table.insert(tab_2,value[i])
i=i+1
end

it seems to be wrong as i know split probably does not return an array but i know that it return different string . How can i manage them .

Upvotes: 1

Views: 811

Answers (2)

moteus
moteus

Reputation: 2235

for line in io.lines('myfile.txt') do
  local v1, v2 = string.match(line, "^(%S+)%s+(%S+)$")
  if v1 and v2 then
    table.insert(tab_1,v1)
    table.insert(tab_2,v2)
  else
    -- wrong line
  end
end

Upvotes: 1

Egor Skriptunoff
Egor Skriptunoff

Reputation: 23727

for line in io.lines'myfile.txt' do
  local v1, v2 = line:match'(.-)%s+(.*)'
  table.insert(tab_1,v1)
  table.insert(tab_2,v2)
end

Upvotes: 1

Related Questions