-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathtranslator.py
More file actions
64 lines (46 loc) · 1.76 KB
/
Copy pathtranslator.py
File metadata and controls
64 lines (46 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
"""Python to lua translator class"""
import ast
import os
from .config import Config
from .nodevisitor import NodeVisitor
class Translator:
"""Python to lua main class translator"""
def __init__(self, config=None, show_ast=False):
self.config = config if config is not None else Config()
self.show_ast = show_ast
self.output = []
def translate(self, pycode):
"""Translate python code to lua code"""
py_ast_tree = ast.parse(pycode)
visitor = NodeVisitor(config=self.config)
if self.show_ast:
print(ast.dump(py_ast_tree))
visitor.visit(py_ast_tree)
self.output = visitor.output
return self.to_code()
def to_code(self, code=None, indent=0):
"""Create a lua code from the compiler output"""
code = code if code is not None else self.output
def add_indentation(line):
"""Add indentation to the given line"""
indentation_width = 4
indentation_space = " "
indent_copy = max(indent, 0)
return indentation_space * indentation_width * indent_copy + line
lines = []
for line in code:
if isinstance(line, str):
lines.append(add_indentation(line))
elif isinstance(line, list):
sub_code = self.to_code(line, indent + 1)
lines.append(sub_code)
return "\n".join(lines)
@staticmethod
def get_luainit(filename="luainit.lua"):
"""Get lua initialization code."""
script_name = os.path.realpath(__file__)
folder = os.path.dirname(script_name)
luainit_path = os.path.join(folder, filename)
with open(luainit_path) as file:
return file.read()
return ""