Reputation: 21
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.
Upvotes: 1
Views: 107
Reputation:
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
Upvotes: 2