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

Looking for a way to automatically parse a program to data

Started by Hexidecimark, 22 January 2017 - 06:58 PM
Hexidecimark #1
Posted 22 January 2017 - 07:58 PM
I've been looking around and I can't seem to find anyone even requesting this-

I've been working on a project to construct a program which is in CC an unprecedented feat.

But I need to be able to get a program to parse each character in another program.

I need to be able to get each character from that line so I can convert the character data to numerical data.

So if startup had "print("hello world")", processing startup would look like;
p, r, i, n, t, (…
[N blank spaces counted, move to next]
[N blank lines counted, end]

I have every other aspect of the system finished.
valithor #2
Posted 23 January 2017 - 01:16 AM
If I am understanding correctly this should help you do what you are wanting:


local h = fs.open("startup","r")

local blankLines = 0 --# variable to keep track of number of blank lines

if h then --# making sure the file was opened
  local line = h.readLine()
  while line do --# looping while the line variable does not equal nil
	local blankSpaces = 0 --# used to keep track of blank spaces in each line
	for i = 1, #line do --# looping through each character (length of the line)
	  local char = string.sub(line,i,i) --# grabbing the character at the current loop iteration
	  if char == " " then --# char is a space
		blankSpaces = blankSpaces + 1
	  else --# char was not a space
		--# do something with the character
	  end
	end
	if blankSpaces == #line then  --# was every character in the line a space?
	  --# do lines that only have spaces count as blank lines?
	  blankLines = blankLines + 1
	elseif #line == 0 then
	  blankLines = blankLines + 1
	end
	line = h.readLine()
  end
end

h.close()

This code is untested, it very well may have errors. It is meant to be more or less of a example to see how to loop through the characters in a line.
Edited on 23 January 2017 - 05:25 AM
Hexidecimark #3
Posted 23 January 2017 - 03:17 AM
Excellent, thank you. This is more than I'd been expecting.

If the program works I'll try and share a copy,
Exerro #4
Posted 24 January 2017 - 06:49 PM
You could also use (from valithor's example)

for line in h.readLine do ...
rather than the while loop/h.readLine() at the end. Also, you'll probably want to count "\t" as a space character.

You might not want to count spaces inside strings too, depending on what you're doing.