Instead it should be:
--space
local a = 1
You won't get that first space because Lua long strings discard the first newline.
Your problem is that your match on "[^\n]+" matches at least one character which is not a newline. An empty line won't match (there are no characters between the newlines) and thus they don't get shown.
Now you can change that to "[^\n]*" like this:
for Paragraph in string.gmatch(code,"[^\n]*") do
print("Line=", Paragraph)
for Word in string.gmatch(Paragraph, "[^ ]+") do
print ("Word=", Word)
end
end
But that has a different problem:
Line= local a = 1
Word= local
Word= a
Word= =
Word= 1
Line=
Line=
Line= local b = 2
Word= local
Word= b
Word= =
Word= 2
Line=
Line=
Blank lines appear twice!
A handy function for iterating through a string, a line at a time, is this:
function getlines (str)
local pos = 0
-- the for loop calls this for every iteration
-- returning nil terminates the loop
local function iterator (s)
if not pos then
return nil
end -- end of string, exit loop
local oldpos = pos + 1 -- step past previous newline
pos = string.find (s, "\n", oldpos) -- find next newline
if not pos then -- no more newlines, return rest of string
return string.sub (s, oldpos)
end -- no newline
return string.sub (s, oldpos, pos - 1)
end -- iterator
return iterator, str
end -- getlines
That handles empty lines. Now you can write your code like this (assuming the function above precedes your code):
for Paragraph in getlines (code) do
print("Line=", Paragraph)
for Word in string.gmatch(Paragraph, "[^ ]+") do
print ("Word=", Word)
end
end
Output:
Line= local a = 1
Word= local
Word= a
Word= =
Word= 1
Line=
Line= local b = 2
Word= local
Word= b
Word= =
Word= 2
Line=
Make a Lua module
You can turn the function getlines into a Lua module, like this:
getlines.lua
function getlines (str)
local pos = 0
-- the for loop calls this for every iteration
-- returning nil terminates the loop
local function iterator (s)
if not pos then
return nil
end -- end of string, exit loop
local oldpos = pos + 1 -- step past previous newline
pos = string.find (s, "\n", oldpos) -- find next newline
if not pos then -- no more newlines, return rest of string
return string.sub (s, oldpos)
end -- no newline
return string.sub (s, oldpos, pos - 1)
end -- iterator
return iterator, str
end -- getlines
return getlines
Now all you have to do is "require" it:
require "getlines"
for Paragraph in getlines (code) do
print("Line=", Paragraph)
for Word in string.gmatch(Paragraph, "[^ ]+") do
print ("Word=", Word)
end
end