lunatic-python
lunatic-python copied to clipboard
in operator has non predictable behavior
It seems the 'in' Python operator has non predictable behavior on Lua tables:
lua.execute ("aaa = { a = 12, b = 13, c = 14 }")
aaa = lua.globals ().aaa
print (aaa)
print ("a" in aaa)
print ("a" in aaa)
results in
<Lua table at 0x65f2e40>
True
False
I guess this should be either True or False, but not both.
In addition, if I ask for "d" instead, it's always False.
It looks to me that 'in' is being implemented by iterating over the table. The LuaObject returns itself as an iterator to Python, so the first time 'in' is used, Python iterates over all the keys and finds that the right key does exist. The second time, Python continues iterating over the LuaObject (again, it returns itself as an iterator) and finishes iterating over the rest of the keys and doesn't find the right key, because it already iterated over it the first time.
So:
- Maybe the LuaObject shouldn't be returning itself as an iterator
- Maybe an 'in' method should be supplied to Python that uses the (more efficient) table lookup instead.
- Maybe for Lua 'lists', the 'in' method should iterate over values, like 'in' works for lists in Python.
On Mon, Jul 1, 2013 at 4:09 PM, benmercs [email protected] wrote:
It seems the 'in' Python operator has non predictable behavior on Lua tables:
lua.execute ("aaa = { a = 12, b = 13, c = 14 }") aaa = lua.globals ().aaa print (aaa) print ("a" in aaa) print ("a" in aaa)
results in
True False
I guess this should be either True or False, but not both.
— Reply to this email directly or view it on GitHubhttps://github.com/bastibe/lunatic-python/issues/16 .
The main problem, is that LuaObject's iterator is acting like a "singleton" for that instance of the variable. You'll find that you can't get 2 separate iterators pointing to different positions in LuaObject since behind the scenes, only one iterator state is being maintained and you always get back that state.
I was looking at trying to get sq_contains to work since that slot supposely handles python's in usage context for custom PyTypeObjects. But for some reason, I can't get python to call the corresponding function for it.
@greatwolf I discovered and fixed this problem
My fork of this project though entirely dirente, had the same problem. I was able to resolve using the code set:
From line https://github.com/alexsilva/lunatic-python/blob/dev-wsgi/src/luainpython.c#L226 Until https://github.com/alexsilva/lunatic-python/blob/dev-wsgi/src/luainpython.c#L305
My tests are simple but prove that the problem is resolved:
https://github.com/alexsilva/lunatic-python/blob/master/tests/python/test.py#L102