我正在尝试在Python中使用COOL编译器,但在我尝试设置全局变量时,它说“NameError:name'commp_reg'未定义”。我在开头定义变量,然后我将它用作全局变量,所以我不明白为什么它不起作用。
有任何想法吗?谢谢。
class CoolLexer(Lexer):
comm_reg = False
comm_line = False
@_(r'[(][\*]')
def COMMENT(self, t):
global comm_reg
comm_reg = True
@_(r'[*][)]')
def CLOSE_COMMENT(self, t):
global comm_reg
if comm_reg:
comm_reg = False
else:
return t
@_(r'[-][-].*')
def ONE_LINE_COMMENT(self, t):
global comm_line
comm_line = True
def salida(self, texto):
list_strings = []
for token in lexer.tokenize(texto):
global comm_line
global comm_reg
if comm_reg:
continue
elif comm_line:
comm_line = False
continue
result = f'#{token.lineno} {token.type} '
看起来你想要这样的东西:
class CoolLexer(Lexer):
def __init__(self):
self.comm_reg = False
self.comm_line = False
@_(r'[(][\*]')
def COMMENT(self, t):
self.comm_reg = True
@_(r'[*][)]')
def CLOSE_COMMENT(self, t):
if self.comm_reg:
self.comm_reg = False
else:
return t
@_(r'[-][-].*')
def ONE_LINE_COMMENT(self, t):
self.comm_line = True
def salida(self, texto):
list_strings = []
for token in self.tokenize(texto):
if self.comm_reg:
continue
elif self.comm_line:
self.comm_line = False
continue
result = f'#{token.lineno} {token.type} '