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

Read Each line and store it as a table

Started by ComputerCraftFan11, 17 May 2012 - 01:24 AM
ComputerCraftFan11 #1
Posted 17 May 2012 - 03:24 AM
I'm trying to create a program to run .bat files. I currently got:

echo
exit
cls
del
execute
title

pause

(And list but that's not included in the code below)

It all works with my built in shell, but how do I make it read line and store it as a table? Kinda like this:


local bExit = false

function eDecode(test)
test = fs.open(test, "r")
for i=1, *number of lines* do
--Read each line and store it as tWords

for match in string.gmatch(sLine, "[^ \t]+") do
table.insert( tWords, match )
end

eBatch(tWords)
end
test.close()
end

function eBatch(tWords)
local sCommand = tWords[1]
if sCommand == "echo" then
print(tWords[2])
elseif sCommand == "exit" then
bExit = true
elseif sCommand == "pause" then
print("Press any key to continue.")
os.pullEvent("key")
sleep(0)
elseif sCommand == "cls" then
term.clear()
term.setCursorPos(1,1)
elseif sCommand == "del" then
if tWords[2] then
if fs.exists(tWords[2]) then
if fs.isReadOnly(tWords[2]) then
print("nul file")
else
fs.delete( tWords[2] )
end
end
end
elseif sCommand == "execute" then --just made this one up, might not exist
if fs.exists(tWords[2]) then
eDecode(tWords[2])
else
print("File does not exist.")
end
elseif sCommand == "title" then
return tWords[2] --Title is pretty much useless here, so i'll just return what they typed for other's programs.
else
print("nul")
end
end

print("BATCH Simulator v0.1")
print("Type 'exit' to exit")

local tCommandHistory = {}
while not bExit do
write( "BATCH_> " )

local sLine = read( nil, tCommandHistory )
table.insert( tCommandHistory, sLine )

local tWords = {}
for match in string.gmatch(sLine, "[^ \t]+") do
table.insert( tWords, match )
end

eBatch(tWords)
end
I'm trying to make a for loop to read each line and store it as a table, then split it up and run each line.

Formatted
libraryaddict #2
Posted 17 May 2012 - 07:18 AM
for line in fsopenVariableThingy:lines() do
print(line)
end
Xtansia #3
Posted 17 May 2012 - 09:45 AM

local tLines = {}
local file = io.open("MyFile", "r")
local line
while true do
    line = file:read()
    if not line then break end
    tLines[#tLines+1] = line
end
file:close()