1

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 .

2
  • tab_1[1] and tab_2[2]? That seems a bit strange. Also, from your code it seems more like you want tab_1[1] and tab_2[1]. Commented Jul 22, 2013 at 10:43
  • yes i was wrong about that ouuups it is tab_1[1] and tab_2[1] Commented Jul 22, 2013 at 11:21

2 Answers 2

1
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
Sign up to request clarification or add additional context in comments.

5 Comments

actually that did not work as expected actually i don't know if i was clear enough but my file contains urls and ip addresses separated by a space it is not just simple words . The second variable v2 does not get any value
Please show an example of string from your text file where v2 gets no value with my code.
i couldnt put the http url as it is because it will be a link
Works fine for me. Test it with another lines and give a link where the problem is.
your code is just fine @Egor it was something wrong with my code and i fix it , thanks for your time and help
1
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.