1

I'm very new to Lua, So sorry if I sound really stupid. I'm trying to make a program that does something a bit like this:

User input: "Hello world" Var1: Hello Var2: world

Because I have no idea what I'm doing, All I have is test = io.read(), And I have no idea what to do next.

I appreciate any help!

Thanks, Morgan.

  • dublicate, e.g.: [stackoverflow](https://stackoverflow.com/questions/1426954/split-string-in-lua) – Mike V. Dec 19 '17 at 12:36

1 Answers1

2

If you want split words, you can do so:

input = "Hello world"

-- declare a table to store the results
-- use tables instead of single variables, if you don't know how many results you'll have
t_result = {}

-- scan the input
for k in input:gmatch('(%w+)') do table.insert(t_result, k) end
-- input:gmatch('(%w+)')
-- with generic match function will the input scanned for matches by the given pattern
-- it's the same like: string.gmatch(input, '(%w+)')
-- meaning of the search pattern:
---- "%w" = word character
---- "+"  = one or more times
---- "()" = capture the match and return it to the searching variable "k"

-- table.insert(t_result, k)
-- each captured occurence of search result will stored in the result table

-- output
for i=1, #t_result do print(t_result[i]) end
-- #t_result: with "#" you get the length of the table (it's not usable for each kind of tables)
-- other way:
-- for k in pairs(t_result) do print(t_result[k]) end

Output:

Hello
world
  • Thank you very much for answering! But I don't really understand what this means. If it Isn't too much bother, would you mind breaking down what each part of the code does, and How I could turn the output into variables? I really appreciate your response. – Mechanical Morgan Dec 18 '17 at 17:51
  • I've now added comments. It's not sensefull, to store results in single variables, if the count of results is unknown. And when the user makes an input, you do not know how many words it will be. –  Dec 19 '17 at 10:04