Lua注释的解析方法

来源:互联网 发布:报纸数据库 编辑:程序博客网 时间:2024/05/21 02:36
之前实验室一个学长跟我一起研究lua的注释格式,特此写了一个lua的注释解析小代码练手,顺便练习递归文法解析。

lua注释格式为 -- XXXX +'\n'或者为 --[n个=[XXX]n个=]

--Lua注释解析--case1:从--开始 若--后面不为[ 则解析到\n为注释--case2:从--开始 若--后面为[ 则必须为[==[XXX]==]的形式 中间等号数相等可为O--str=[[  --[==[sadsadasdas]==]  ]]function GetChar(i)return string.sub(str,i,i);endfunction StrMatch(i,j,pattern)return string.sub(s,i,j)==pattern;endfunction EscapeWhiteSpaces(i)local strlen=string.len(str);local e=i;while e<strlen doif GetChar(i)==' ' thene=e+1;elsebreak;endendendfunction EscapeComments(i)local strlen=string.len(str);if StrMatch(i,i+3,"--[") thenlocal e=i+3;if StrMatch(e,e+1,"[") thenlocal right="]"..string.sub(str,i+3,e).."]";local len=e-i-1;e=e+1;while e+len<= strlen and string.sub(str,e,e+len)==right doe=e+1;endif e+len>strlen thenprint("comment error!");elsereturn e+lenendelsewhile e<strlen and GetChar(e)~='\n' doe=e+1;endreturn e+1;endelselocal e=i+2;while e<strlen and GetChar(e)~='\n' doe=e+1;endreturn e+1;endendfunction Escape(i)local strlen=string.len(str);while i<strlen doi=EscapeWhiteSpaces(i);if StrMatch(i,i+2,"--") theni=EscapeComments(i);elsebreak;endendend


原创粉丝点击