Skip to content

Commit e030daa

Browse files
Added 'in' and 'not in' operators
1 parent 33a7832 commit e030daa

File tree

5 files changed

+63
-3
lines changed

5 files changed

+63
-3
lines changed

pythonlua/cmpopdesc.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,10 @@ class CompareOperationDesc:
1212
ast.LtE: "<=",
1313
ast.Gt: ">",
1414
ast.GtE: ">=",
15+
ast.In: {
16+
"format": "operator_in({left}, {right})",
17+
},
18+
ast.NotIn: {
19+
"format": "not operator_in({left}, {right})",
20+
},
1521
}

pythonlua/luainit.lua

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,9 @@ local function list(t)
7070
return v
7171
end,
7272
})
73+
74+
t.is_list = true
75+
7376
return t
7477
end
7578

@@ -94,6 +97,8 @@ function dict(t)
9497
return key_index
9598
end,
9699
})
100+
101+
t.is_dict = true
97102

98103
return t
99104
end
@@ -122,6 +127,20 @@ local function staticmethod(old_fun)
122127
return wrapper
123128
end
124129

130+
local function operator_in(item, items)
131+
if type(items) == "table" then
132+
for v in items do
133+
if v == item then
134+
return true
135+
end
136+
end
137+
elseif type(items) == "string" and type(item) == "string" then
138+
return string.find(items, item, 1, true) ~= nil
139+
end
140+
141+
return false
142+
end
143+
125144
-- Lua classes
126145
local function class(class_init, bases)
127146
bases = bases or {}
@@ -168,4 +187,5 @@ local function class(class_init, bases)
168187
end
169188
--[[
170189
End of the lua pythonization.
171-
--]]
190+
--]]
191+

pythonlua/nodevisitor.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -147,10 +147,14 @@ def visit_Compare(self, node):
147147

148148
values = {
149149
"left": left,
150-
"op": operation,
151150
"right": right,
152151
}
153-
line += "{left} {op} {right}".format(**values)
152+
153+
if isinstance(operation, str):
154+
values["op"] = operation
155+
line += "{left} {op} {right}".format(**values)
156+
elif isinstance(operation, dict):
157+
line += operation["format"].format(**values)
154158

155159
if i < len(node.ops) - 1:
156160
left = right

tests/in.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
a = [1, 2, 3, 4]
2+
b = {
3+
"name": "John",
4+
"age": 42,
5+
}
6+
7+
c = "Hello, world!"
8+
9+
if 2 < 3:
10+
print("2 < 3")
11+
12+
print(1 in a)
13+
print(2 in a)
14+
print(5 in a)
15+
print("name" in b)
16+
print("surname" in b)
17+
print("Hell" in c)
18+
print("world" in c)
19+
print("Foo" in c)
20+
print("Hells" not in c)

tests/in.py.expected

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
2 < 3
2+
true
3+
true
4+
false
5+
true
6+
false
7+
true
8+
true
9+
false
10+
true

0 commit comments

Comments
 (0)