This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Dave-ee Jones's profile picture

Deleting whitespace at start of string but not at end

Started by Dave-ee Jones, 13 October 2017 - 04:21 AM
Dave-ee Jones #1
Posted 13 October 2017 - 06:21 AM
Hoi!

So, I've got my programming language parser working pretty mint but then realised that it's removing the whitespace on the end of a line. So if I've got a snippet that looks like this:

<color[red,white]>
<write>
  hey!
  what's up?
</write>
</color>

And I have a space write after 'hey!' on the same line (e.g. 'hey! ') then it will remove the space after 'hey!', which is what I don't want because I want 'what's up?' to appear a space after 'hey!', if you catch my drift.

Here's my current whitespace-removing-technique:

_line:match("^%s*(.-)%s*$")

It removes the whitespace line-by-line.

Any help is appreciated. I'm assuming it's just an alteration to the current 'string:match(..)' I have, but since I'm not familiar with the character codes I cannot figure it out myself (maybe remove '(.-)%s*$' at the end?).
Edited on 13 October 2017 - 04:25 AM
Kepler #2
Posted 13 October 2017 - 06:50 AM
Here's what I use:

http://snippets.luac..._from_string_76

function trim(s)
  return s:find'^%s*$' and '' or s:match'^%s*(.*%S)'
end

-- trim whitespace from left end of string
function triml(s)
  return s:match'^%s*(.*)'
end

-- trim whitespace from right end of string
function trimr(s)
  return s:find'^%s*$' and '' or s:match'^(.*%S)'
end
Edited on 13 October 2017 - 04:53 AM
Grim Reaper #3
Posted 15 October 2017 - 06:33 AM
If I understand what you're asking, here's a quick solution I thought up. My Lua skills are rusty, but the test scenario you described checks out.


local codeSnippet =
[[
hey!
what's up?
]]

local function parseLineTrimWhiteSpaceAtBackKeepAtFront(line)
   return line:match("[%s]*([^%s]*%s*)")
end

local function parseSnippetIntoSingleLine(codeSnippet)
   local parsedLines = {}
   local lineNumber = 1
   for line in codeSnippet:gmatch("[^\n+]+") do
	  parsedLines[lineNumber] = line
	  lineNumber = lineNumber + 1
   end
   return parsedLines
end

local function combineParsedLinesIntoSingleLine(parsedLines)
   local combinedLine = ""
   for _, line in ipairs(parsedLines) do
	   combinedLine = combinedLine .. line
   end
   return combinedLine
end

local function getContentLineFromCodeSnippet(codeSnippet)
   local parsedLines = parseSnippetIntoSingleLine(codeSnippet)
   return combineParsedLinesIntoSingleLine(parsedLines)
end

print(getContentLineFromCodeSnippet(codeSnippet))
-- Output (quotes to define string start/stop): "hey! what's up?"
Edited on 15 October 2017 - 04:33 AM