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

Changing characters after %s+.+%s

Started by johnnic, 09 June 2014 - 02:04 AM
johnnic #1
Posted 09 June 2014 - 04:04 AM
I am working on a program that changes my code from a java/lua mix into pure lua, and i was trying to change the java operator "while(conditional){" into "while conditional do" by using string:gsub. The code used is:

local args={...};
local repls={
awhile={"while%(%s+.+%s+%){","while%s+.+%s+do"},
sif={"if%(","if "},
eif={"%)then"," then"},
alteif={"%) then"," then"},
pfor={"for%(","for "},
pwhile={"while%(","while "},
aforwhile={"%)do"," do"},
altaforwhile={"%) do"," do"},
rand={"&&"," and "},
ror={"||"," or "},
rnot={"!"," not "},
rend={"}","end"}
}
if not #args<=2 then
print("Only 1 arg needed");
return;
end
t={};
print("prefor");
file=fs.open(args[1],"r");
local sLine=file.readLine();
while sLine do
for f,y in pairs(repls) do
  sLine=sLine:gsub(y[1],y[2]);
end
table.insert(t,sLine);
sLine=file.readLine();
end
file.close();
file=fs.open(args[1]..".c","w");
for f,y in pairs(t) do
file.write(y.."\n");
end
file.close();
I used this input file:

while(true){
	print("Hi");
	return;
}
The expected output was:

while true do
	print("Hi");
	return;
end
The actual output was:

while true){
	print("Hi");
	return;
end
Can anyone tell me a way to close the %s+.+%s? Thanks in advance

EDIT: It will not keep my code indented. Help? Sorry
Edited on 09 June 2014 - 02:04 AM
Bomb Bloke #2
Posted 09 June 2014 - 07:47 AM
Can anyone tell me a way to close the %s+.+%s? Thanks in advance

I'm not exactly a pattern expert, but this should be what you're after:

awhile={"(while%s*%(%s*)(.-)(%)%s*%{)","while %2 do"}

You'd want to ditch pwhile, aforwhile and altaforwhile from your table with it in place.

It searches for three terms - "while%s*%(%s*" is %1, ".-" is %2 and "%)%s*%{" is %3.

%1 and %3 then get ditched, leaving %2 wrapped in the replacement code.

Be wary of using ".+", which basically states "grab whatever's left of the line".

EDIT: It will not keep my code indented. Help? Sorry

Turn off the rich text editor (using the little light switch icon at the top-left of the posting box).