Debian Codegraph @

PKG-INFO

raw
1 Metadata-Version: 2.2
2 Name: lupa
3 Version: 2.4
4 Summary: Python wrapper around Lua and LuaJIT
5 Home-page: https://github.com/scoder/lupa
6 Author: Stefan Behnel
7 Author-email: [email protected]
8 Maintainer: Lupa-dev mailing list
9 Maintainer-email: [email protected]
10 License: MIT style
11 Classifier: Development Status :: 5 - Production/Stable
12 Classifier: Intended Audience :: Developers
13 Classifier: Intended Audience :: Information Technology
14 Classifier: License :: OSI Approved :: MIT License
15 Classifier: Programming Language :: Cython
16 Classifier: Programming Language :: Python :: 3
17 Classifier: Programming Language :: Lua
18 Classifier: Programming Language :: Other Scripting Engines
19 Classifier: Operating System :: OS Independent
20 Classifier: Topic :: Software Development
21 License-File: LICENSE.txt
22 Dynamic: author
23 Dynamic: author-email
24 Dynamic: classifier
25 Dynamic: description
26 Dynamic: home-page
27 Dynamic: license
28 Dynamic: maintainer
29 Dynamic: maintainer-email
30 Dynamic: summary
31
32 Lupa
33 ====
34
35 .. image:: logo/logo-220x200.png
36
37 Lupa integrates the runtimes of Lua_ or LuaJIT2_ into CPython.
38 It is a partial rewrite of LunaticPython_ in Cython_ with some
39 additional features such as proper coroutine support.
40
41 .. _Lua: http://lua.org/
42 .. _LuaJIT2: http://luajit.org/
43 .. _LunaticPython: http://labix.org/lunatic-python
44 .. _Cython: http://cython.org
45
46 For questions not answered here, please contact the `Lupa mailing list`_.
47
48 .. _`Lupa mailing list`: http://www.freelists.org/list/lupa-dev
49
50 .. contents:: :local:
51
52
53 Major features
54 --------------
55
56 * separate Lua runtime states through a ``LuaRuntime`` class
57
58 * Python coroutine wrapper for Lua coroutines
59
60 * iteration support for Python objects in Lua and Lua objects in
61 Python
62
63 * proper encoding and decoding of strings (configurable per runtime,
64 UTF-8 by default)
65
66 * frees the GIL and supports threading in separate runtimes when
67 calling into Lua
68
69 * tested with Python 2.7/3.6 and later
70
71 * ships with Lua 5.1, 5.2, 5.3 and 5.4
72 as well as LuaJIT 2.0 and 2.1 on systems that support it.
73
74 * easy to hack on and extend as it is written in Cython, not C
75
76
77 Why the name?
78 -------------
79
80 In Latin, "lupa" is a female wolf, as elegant and wild as it sounds.
81 If you don't like this kind of straight forward allegory to an
82 endangered species, you may also happily assume it's just an
83 amalgamation of the phonetic sounds that start the words "Lua" and
84 "Python", two from each to keep the balance.
85
86
87 Why use it?
88 -----------
89
90 It complements Python very well. Lua is a language as dynamic as
91 Python, but LuaJIT compiles it to very fast machine code, sometimes
92 faster than many statically compiled languages for computational code.
93 The language runtime is very small and carefully designed for
94 embedding. The complete binary module of Lupa, including a statically
95 linked LuaJIT2 runtime, only weighs some 800KB on a 64 bit machine.
96 With standard Lua 5.2, it's less than 600KB.
97
98 However, the Lua ecosystem lacks many of the batteries that Python
99 readily includes, either directly in its standard library or as third
100 party packages. This makes real-world Lua applications harder to write
101 than equivalent Python applications. Lua is therefore not commonly
102 used as primary language for large applications, but it makes for a
103 fast, high-level and resource-friendly backup language inside of
104 Python when raw speed is required and the edit-compile-run cycle of
105 binary extension modules is too heavy and too static for agile
106 development or hot-deployment.
107
108 Lupa is a very fast and thin wrapper around Lua or LuaJIT. It makes it
109 easy to write dynamic Lua code that accompanies dynamic Python code by
110 switching between the two languages at runtime, based on the tradeoff
111 between simplicity and speed.
112
113
114 Which Lua version?
115 ------------------
116
117 The binary wheels include different Lua versions as well as LuaJIT, if supported.
118 By default, ``import lupa`` uses the latest Lua version, but you can choose
119 a specific one via import:
120
121 .. code:: python
122
123 try:
124 import lupa.luajit21 as lupa
125 except ImportError:
126 try:
127 import lupa.lua54 as lupa
128 except ImportError:
129 try:
130 import lupa.lua53 as lupa
131 except ImportError:
132 import lupa
133
134 print(f"Using {lupa.LuaRuntime().lua_implementation} (compiled with {lupa.LUA_VERSION})")
135
136
137 Examples
138 --------
139
140 ..
141 >>> import lupa.lua54 as lupa
142
143 ## doctest helpers:
144 >>> try: _ = sorted
145 ... except NameError:
146 ... def sorted(seq):
147 ... l = list(seq)
148 ... l.sort()
149 ... return l
150
151 .. code:: python
152
153 >>> from lupa.lua54 import LuaRuntime
154 >>> lua = LuaRuntime(unpack_returned_tuples=True)
155
156 >>> lua.eval('1+1')
157 2
158
159 >>> lua_func = lua.eval('function(f, n) return f(n) end')
160
161 >>> def py_add1(n): return n+1
162 >>> lua_func(py_add1, 2)
163 3
164
165 >>> lua.eval('python.eval(" 2 ** 2 ")') == 4
166 True
167 >>> lua.eval('python.builtins.str(4)') == '4'
168 True
169
170 The function ``lua_type(obj)`` can be used to find out the type of a
171 wrapped Lua object in Python code, as provided by Lua's ``type()``
172 function:
173
174 .. code:: python
175
176 >>> lupa.lua_type(lua_func)
177 'function'
178 >>> lupa.lua_type(lua.eval('{}'))
179 'table'
180
181 To help in distinguishing between wrapped Lua objects and normal
182 Python objects, it returns ``None`` for the latter:
183
184 .. code:: python
185
186 >>> lupa.lua_type(123) is None
187 True
188 >>> lupa.lua_type('abc') is None
189 True
190 >>> lupa.lua_type({}) is None
191 True
192
193 Note the flag ``unpack_returned_tuples=True`` that is passed to create
194 the Lua runtime. It is new in Lupa 0.21 and changes the behaviour of
195 tuples that get returned by Python functions. With this flag, they
196 explode into separate Lua values:
197
198 .. code:: python
199
200 >>> lua.execute('a,b,c = python.eval("(1,2)")')
201 >>> g = lua.globals()
202 >>> g.a
203 1
204 >>> g.b
205 2
206 >>> g.c is None
207 True
208
209 When set to False, functions that return a tuple pass it through to the
210 Lua code:
211
212 .. code:: python
213
214 >>> non_explode_lua = lupa.LuaRuntime(unpack_returned_tuples=False)
215 >>> non_explode_lua.execute('a,b,c = python.eval("(1,2)")')
216 >>> g = non_explode_lua.globals()
217 >>> g.a
218 (1, 2)
219 >>> g.b is None
220 True
221 >>> g.c is None
222 True
223
224 Since the default behaviour (to not explode tuples) might change in a
225 later version of Lupa, it is best to always pass this flag explicitly.
226
227
228 Python objects in Lua
229 ---------------------
230
231 Python objects are either converted when passed into Lua (e.g.
232 numbers and strings) or passed as wrapped object references.
233
234 .. code:: python
235
236 >>> wrapped_type = lua.globals().type # Lua's own type() function
237 >>> wrapped_type(1) == 'number'
238 True
239 >>> wrapped_type('abc') == 'string'
240 True
241
242 Wrapped Lua objects get unwrapped when they are passed back into Lua,
243 and arbitrary Python objects get wrapped in different ways:
244
245 .. code:: python
246
247 >>> wrapped_type(wrapped_type) == 'function' # unwrapped Lua function
248 True
249 >>> wrapped_type(len) == 'userdata' # wrapped Python function
250 True
251 >>> wrapped_type([]) == 'userdata' # wrapped Python object
252 True
253
254 Lua supports two main protocols on objects: calling and indexing. It
255 does not distinguish between attribute access and item access like
256 Python does, so the Lua operations ``obj[x]`` and ``obj.x`` both map
257 to indexing. To decide which Python protocol to use for Lua wrapped
258 objects, Lupa employs a simple heuristic.
259
260 Pratically all Python objects allow attribute access, so if the object
261 also has a ``__getitem__`` method, it is preferred when turning it
262 into an indexable Lua object. Otherwise, it becomes a simple object
263 that uses attribute access for indexing from inside Lua.
264
265 Obviously, this heuristic will fail to provide the required behaviour
266 in many cases, e.g. when attribute access is required to an object
267 that happens to support item access. To be explicit about the
268 protocol that should be used, Lupa provides the helper functions
269 ``as_attrgetter()`` and ``as_itemgetter()`` that restrict the view on
270 an object to a certain protocol, both from Python and from inside
271 Lua:
272
273 .. code:: python
274
275 >>> lua_func = lua.eval('function(obj) return obj["get"] end')
276 >>> d = {'get' : 'value'}
277
278 >>> value = lua_func(d)
279 >>> value == d['get'] == 'value'
280 True
281
282 >>> value = lua_func( lupa.as_itemgetter(d) )
283 >>> value == d['get'] == 'value'
284 True
285
286 >>> dict_get = lua_func( lupa.as_attrgetter(d) )
287 >>> dict_get == d.get
288 True
289 >>> dict_get('get') == d.get('get') == 'value'
290 True
291
292 >>> lua_func = lua.eval(
293 ... 'function(obj) return python.as_attrgetter(obj)["get"] end')
294 >>> dict_get = lua_func(d)
295 >>> dict_get('get') == d.get('get') == 'value'
296 True
297
298 Note that unlike Lua function objects, callable Python objects support
299 indexing in Lua:
300
301 .. code:: python
302
303 >>> def py_func(): pass
304 >>> py_func.ATTR = 2
305
306 >>> lua_func = lua.eval('function(obj) return obj.ATTR end')
307 >>> lua_func(py_func)
308 2
309 >>> lua_func = lua.eval(
310 ... 'function(obj) return python.as_attrgetter(obj).ATTR end')
311 >>> lua_func(py_func)
312 2
313 >>> lua_func = lua.eval(
314 ... 'function(obj) return python.as_attrgetter(obj)["ATTR"] end')
315 >>> lua_func(py_func)
316 2
317
318
319 Iteration in Lua
320 ----------------
321
322 Iteration over Python objects from Lua's for-loop is fully supported.
323 However, Python iterables need to be converted using one of the
324 utility functions which are described here. This is similar to the
325 functions like ``pairs()`` in Lua.
326
327 To iterate over a plain Python iterable, use the ``python.iter()``
328 function. For example, you can manually copy a Python list into a Lua
329 table like this:
330
331 .. code:: python
332
333 >>> lua_copy = lua.eval('''
334 ... function(L)
335 ... local t, i = {}, 1
336 ... for item in python.iter(L) do
337 ... t[i] = item
338 ... i = i + 1
339 ... end
340 ... return t
341 ... end
342 ... ''')
343
344 >>> table = lua_copy([1,2,3,4])
345 >>> len(table)
346 4
347 >>> table[1] # Lua indexing
348 1
349
350 Python's ``enumerate()`` function is also supported, so the above
351 could be simplified to:
352
353 .. code:: python
354
355 >>> lua_copy = lua.eval('''
356 ... function(L)
357 ... local t = {}
358 ... for index, item in python.enumerate(L) do
359 ... t[ index+1 ] = item
360 ... end
361 ... return t
362 ... end
363 ... ''')
364
365 >>> table = lua_copy([1,2,3,4])
366 >>> len(table)
367 4
368 >>> table[1] # Lua indexing
369 1
370
371 For iterators that return tuples, such as ``dict.iteritems()``, it is
372 convenient to use the special ``python.iterex()`` function that
373 automatically explodes the tuple items into separate Lua arguments:
374
375 .. code:: python
376
377 >>> lua_copy = lua.eval('''
378 ... function(d)
379 ... local t = {}
380 ... for key, value in python.iterex(d.items()) do
381 ... t[key] = value
382 ... end
383 ... return t
384 ... end
385 ... ''')
386
387 >>> d = dict(a=1, b=2, c=3)
388 >>> table = lua_copy( lupa.as_attrgetter(d) )
389 >>> table['b']
390 2
391
392 Note that accessing the ``d.items`` method from Lua requires passing
393 the dict as ``attrgetter``. Otherwise, attribute access in Lua would
394 use the ``getitem`` protocol of Python dicts and look up ``d['items']``
395 instead.
396
397
398 None vs. nil
399 ------------
400
401 While ``None`` in Python and ``nil`` in Lua differ in their semantics, they
402 usually just mean the same thing: no value. Lupa therefore tries to map one
403 directly to the other whenever possible:
404
405 .. code:: python
406
407 >>> lua.eval('nil') is None
408 True
409 >>> is_nil = lua.eval('function(x) return x == nil end')
410 >>> is_nil(None)
411 True
412
413 The only place where this cannot work is during iteration, because Lua
414 considers a ``nil`` value the termination marker of iterators. Therefore,
415 Lupa special cases ``None`` values here and replaces them by a constant
416 ``python.none`` instead of returning ``nil``:
417
418 .. code:: python
419
420 >>> _ = lua.require("table")
421 >>> func = lua.eval('''
422 ... function(items)
423 ... local t = {}
424 ... for value in python.iter(items) do
425 ... table.insert(t, value == python.none)
426 ... end
427 ... return t
428 ... end
429 ... ''')
430
431 >>> items = [1, None ,2]
432 >>> list(func(items).values())
433 [False, True, False]
434
435 Lupa avoids this value escaping whenever it's obviously not necessary.
436 Thus, when unpacking tuples during iteration, only the first value will
437 be subject to ``python.none`` replacement, as Lua does not look at the
438 other items for loop termination anymore. And on ``enumerate()``
439 iteration, the first value is known to be always a number and never None,
440 so no replacement is needed.
441
442 .. code:: python
443
444 >>> func = lua.eval('''
445 ... function(items)
446 ... for a, b, c, d in python.iterex(items) do
447 ... return {a == python.none, a == nil, --> a == python.none
448 ... b == python.none, b == nil, --> b == nil
449 ... c == python.none, c == nil, --> c == nil
450 ... d == python.none, d == nil} --> d == nil ...
451 ... end
452 ... end
453 ... ''')
454
455 >>> items = [(None, None, None, None)]
456 >>> list(func(items).values())
457 [True, False, False, True, False, True, False, True]
458
459 >>> items = [(None, None)] # note: no values for c/d => nil in Lua
460 >>> list(func(items).values())
461 [True, False, False, True, False, True, False, True]
462
463
464 Note that this behaviour changed in Lupa 1.0. Previously, the ``python.none``
465 replacement was done in more places, which made it not always very predictable.
466
467
468 Lua Tables
469 ----------
470
471 Lua tables mimic Python's mapping protocol. For the special case of
472 array tables, Lua automatically inserts integer indices as keys into
473 the table. Therefore, indexing starts from 1 as in Lua instead of 0
474 as in Python. For the same reason, negative indexing does not work.
475 It is best to think of Lua tables as mappings rather than arrays, even
476 for plain array tables.
477
478 .. code:: python
479
480 >>> table = lua.eval('{10,20,30,40}')
481 >>> table[1]
482 10
483 >>> table[4]
484 40
485 >>> list(table)
486 [1, 2, 3, 4]
487 >>> dict(table)
488 {1: 10, 2: 20, 3: 30, 4: 40}
489 >>> list(table.values())
490 [10, 20, 30, 40]
491 >>> len(table)
492 4
493
494 >>> mapping = lua.eval('{ [1] = -1 }')
495 >>> list(mapping)
496 [1]
497
498 >>> mapping = lua.eval('{ [20] = -20; [3] = -3 }')
499 >>> mapping[20]
500 -20
501 >>> mapping[3]
502 -3
503 >>> sorted(mapping.values())
504 [-20, -3]
505 >>> sorted(mapping.items())
506 [(3, -3), (20, -20)]
507
508 >>> mapping[-3] = 3 # -3 used as key, not index!
509 >>> mapping[-3]
510 3
511 >>> sorted(mapping)
512 [-3, 3, 20]
513 >>> sorted(mapping.items())
514 [(-3, 3), (3, -3), (20, -20)]
515
516 To simplify the table creation from Python, the ``LuaRuntime`` comes with
517 a helper method that creates a Lua table from Python arguments:
518
519 .. code:: python
520
521 >>> t = lua.table(10, 20, 30, 40)
522 >>> lupa.lua_type(t)
523 'table'
524 >>> list(t)
525 [1, 2, 3, 4]
526 >>> list(t.values())
527 [10, 20, 30, 40]
528
529 >>> t = lua.table(10, 20, 30, 40, a=1, b=2)
530 >>> t[3]
531 30
532 >>> t['b']
533 2
534
535 A second helper method, ``.table_from()``, was added in Lupa 1.1 and accepts
536 any number of mappings and sequences/iterables as arguments. It collects
537 all values and key-value pairs and builds a single Lua table from them.
538 Any keys that appear in multiple mappings get overwritten with their last
539 value (going from left to right).
540
541 .. code:: python
542
543 >>> t = lua.table_from([10, 20, 30], {'a': 11, 'b': 22}, (40, 50), {'b': 42})
544 >>> t['a']
545 11
546 >>> t['b']
547 42
548 >>> t[5]
549 50
550 >>> sorted(t.values())
551 [10, 11, 20, 30, 40, 42, 50]
552
553 Since Lupa 2.1, passing ``recursive=True`` will map data structures recursively
554 to Lua tables.
555
556 .. code:: python
557
558 >>> t = lua.table_from(
559 ... [
560 ... # t1:
561 ... [
562 ... [10, 20, 30],
563 ... {'a': 11, 'b': 22}
564 ... ],
565 ... # t2:
566 ... [
567 ... (40, 50),
568 ... {'b': 42}
569 ... ]
570 ... ],
571 ... recursive=True
572 ... )
573 >>> t1, t2 = t.values()
574 >>> list(t1[1].values())
575 [10, 20, 30]
576 >>> t1[2]['a']
577 11
578 >>> t1[2]['b']
579 22
580 >>> t2[2]['b']
581 42
582 >>> list(t1[1].values())
583 [10, 20, 30]
584 >>> list(t2[1].values())
585 [40, 50]
586
587 A lookup of non-existing keys or indices returns None (actually ``nil``
588 inside of Lua). A lookup is therefore more similar to the ``.get()``
589 method of Python dicts than to a mapping lookup in Python.
590
591 .. code:: python
592
593 >>> table = lua.table(10, 20, 30, 40)
594 >>> table[1000000] is None
595 True
596 >>> table['no such key'] is None
597 True
598
599 >>> mapping = lua.eval('{ [20] = -20; [3] = -3 }')
600 >>> mapping['no such key'] is None
601 True
602
603 Note that ``len()`` does the right thing for array tables but does not
604 work on mappings:
605
606 .. code:: python
607
608 >>> len(table)
609 4
610 >>> len(mapping)
611 0
612
613 This is because ``len()`` is based on the ``#`` (length) operator in
614 Lua and because of the way Lua defines the length of a table.
615 Remember that unset table indices always return ``nil``, including
616 indices outside of the table size. Thus, Lua basically looks for an
617 index that returns ``nil`` and returns the index before that. This
618 works well for array tables that do not contain ``nil`` values, gives
619 barely predictable results for tables with 'holes' and does not work
620 at all for mapping tables. For tables with both sequential and
621 mapping content, this ignores the mapping part completely.
622
623 Note that it is best not to rely on the behaviour of len() for
624 mappings. It might change in a later version of Lupa.
625
626 Similar to the table interface provided by Lua, Lupa also supports
627 attribute access to table members:
628
629 .. code:: python
630
631 >>> table = lua.eval('{ a=1, b=2 }')
632 >>> table.a, table.b
633 (1, 2)
634 >>> table.a == table['a']
635 True
636
637 This enables access to Lua 'methods' that are associated with a table,
638 as used by the standard library modules:
639
640 .. code:: python
641
642 >>> string = lua.eval('string') # get the 'string' library table
643 >>> print( string.lower('A') )
644 a
645
646
647 Python Callables
648 ----------------
649
650 As discussed earlier, Lupa allows Lua scripts to call Python functions
651 and methods:
652
653 .. code:: python
654
655 >>> def add_one(num):
656 ... return num + 1
657 >>> lua_func = lua.eval('function(num, py_func) return py_func(num) end')
658 >>> lua_func(48, add_one)
659 49
660
661 >>> class MyClass():
662 ... def my_method(self):
663 ... return 345
664 >>> obj = MyClass()
665 >>> lua_func = lua.eval('function(py_obj) return py_obj:my_method() end')
666 >>> lua_func(obj)
667 345
668
669 Lua doesn't have a dedicated syntax for named arguments, so by default
670 Python callables can only be called using positional arguments.
671
672 A common pattern for implementing named arguments in Lua is passing them
673 in a table as the first and only function argument. See
674 http://lua-users.org/wiki/NamedParameters for more details. Lupa supports
675 this pattern by providing two decorators: ``lupa.unpacks_lua_table``
676 for Python functions and ``lupa.unpacks_lua_table_method`` for methods
677 of Python objects.
678
679 Python functions/methods wrapped in these decorators can be called from
680 Lua code as ``func(foo, bar)``, ``func{foo=foo, bar=bar}``
681 or ``func{foo, bar=bar}``. Example:
682
683 .. code:: python
684
685 >>> @lupa.unpacks_lua_table
686 ... def add(a, b):
687 ... return a + b
688 >>> lua_func = lua.eval('function(a, b, py_func) return py_func{a=a, b=b} end')
689 >>> lua_func(5, 6, add)
690 11
691 >>> lua_func = lua.eval('function(a, b, py_func) return py_func{a, b=b} end')
692 >>> lua_func(5, 6, add)
693 11
694
695 If you do not control the function implementation, you can also just
696 manually wrap a callable object when passing it into Lupa:
697
698 .. code:: python
699
700 >>> import operator
701 >>> wrapped_py_add = lupa.unpacks_lua_table(operator.add)
702
703 >>> lua_func = lua.eval('function(a, b, py_func) return py_func{a, b} end')
704 >>> lua_func(5, 6, wrapped_py_add)
705 11
706
707 There are some limitations:
708
709 1. Avoid using ``lupa.unpacks_lua_table`` and ``lupa.unpacks_lua_table_method``
710 for functions where the first argument can be a Lua table. In this case
711 ``py_func{foo=bar}`` (which is the same as ``py_func({foo=bar})`` in Lua)
712 becomes ambiguous: it could mean either "call ``py_func`` with a named
713 ``foo`` argument" or "call ``py_func`` with a positional ``{foo=bar}``
714 argument".
715
716 2. One should be careful with passing ``nil`` values to callables wrapped in
717 ``lupa.unpacks_lua_table`` or ``lupa.unpacks_lua_table_method`` decorators.
718 Depending on the context, passing ``nil`` as a parameter can mean either
719 "omit a parameter" or "pass None". This even depends on the Lua version.
720
721 It is possible to use ``python.none`` instead of ``nil`` to pass None values
722 robustly. Arguments with ``nil`` values are also fine when standard braces
723 ``func(a, b, c)`` syntax is used.
724
725 Because of these limitations lupa doesn't enable named arguments for all
726 Python callables automatically. Decorators allow to enable named arguments
727 on a per-callable basis.
728
729
730 Lua Coroutines
731 --------------
732
733 The next is an example of Lua coroutines. A wrapped Lua coroutine
734 behaves exactly like a Python coroutine. It needs to get created at
735 the beginning, either by using the ``.coroutine()`` method of a
736 function or by creating it in Lua code. Then, values can be sent into
737 it using the ``.send()`` method or it can be iterated over. Note that
738 the ``.throw()`` method is not supported, though.
739
740 .. code:: python
741
742 >>> lua_code = '''\
743 ... function(N)
744 ... for i=0,N do
745 ... coroutine.yield( i%2 )
746 ... end
747 ... end
748 ... '''
749 >>> lua = LuaRuntime()
750 >>> f = lua.eval(lua_code)
751
752 >>> gen = f.coroutine(4)
753 >>> list(enumerate(gen))
754 [(0, 0), (1, 1), (2, 0), (3, 1), (4, 0)]
755
756 An example where values are passed into the coroutine using its
757 ``.send()`` method:
758
759 .. code:: python
760
761 >>> lua_code = '''\
762 ... function()
763 ... local t,i = {},0
764 ... local value = coroutine.yield()
765 ... while value do
766 ... t[i] = value
767 ... i = i + 1
768 ... value = coroutine.yield()
769 ... end
770 ... return t
771 ... end
772 ... '''
773 >>> f = lua.eval(lua_code)
774
775 >>> co = f.coroutine() # create coroutine
776 >>> co.send(None) # start coroutine (stops at first yield)
777
778 >>> for i in range(3):
779 ... co.send(i*2)
780
781 >>> mapping = co.send(None) # loop termination signal
782 >>> sorted(mapping.items())
783 [(0, 0), (1, 2), (2, 4)]
784
785 It also works to create coroutines in Lua and to pass them back into
786 Python space:
787
788 .. code:: python
789
790 >>> lua_code = '''\
791 ... function f(N)
792 ... for i=0,N do
793 ... coroutine.yield( i%2 )
794 ... end
795 ... end ;
796 ... co1 = coroutine.create(f) ;
797 ... co2 = coroutine.create(f) ;
798 ...
799 ... status, first_result = coroutine.resume(co2, 2) ; -- starting!
800 ...
801 ... return f, co1, co2, status, first_result
802 ... '''
803
804 >>> lua = LuaRuntime()
805 >>> f, co, lua_gen, status, first_result = lua.execute(lua_code)
806
807 >>> # a running coroutine:
808
809 >>> status
810 True
811 >>> first_result
812 0
813 >>> list(lua_gen)
814 [1, 0]
815 >>> list(lua_gen)
816 []
817
818 >>> # an uninitialised coroutine:
819
820 >>> gen = co(4)
821 >>> list(enumerate(gen))
822 [(0, 0), (1, 1), (2, 0), (3, 1), (4, 0)]
823
824 >>> gen = co(2)
825 >>> list(enumerate(gen))
826 [(0, 0), (1, 1), (2, 0)]
827
828 >>> # a plain function:
829
830 >>> gen = f.coroutine(4)
831 >>> list(enumerate(gen))
832 [(0, 0), (1, 1), (2, 0), (3, 1), (4, 0)]
833
834
835 Threading
836 ---------
837
838 The following example calculates a mandelbrot image in parallel
839 threads and displays the result in PIL. It is based on a `benchmark
840 implementation`_ for the `Computer Language Benchmarks Game`_.
841
842 .. _`Computer Language Benchmarks Game`: http://shootout.alioth.debian.org/u64/benchmark.php?test=all&lang=luajit&lang2=python3
843 .. _`benchmark implementation`: http://shootout.alioth.debian.org/u64/program.php?test=mandelbrot&lang=luajit&id=1
844
845 .. code:: python
846
847 lua_code = '''\
848 function(N, i, total)
849 local char, unpack = string.char, table.unpack
850 local result = ""
851 local M, ba, bb, buf = 2/N, 2^(N%8+1)-1, 2^(8-N%8), {}
852 local start_line, end_line = N/total * (i-1), N/total * i - 1
853 for y=start_line,end_line do
854 local Ci, b, p = y*M-1, 1, 0
855 for x=0,N-1 do
856 local Cr = x*M-1.5
857 local Zr, Zi, Zrq, Ziq = Cr, Ci, Cr*Cr, Ci*Ci
858 b = b + b
859 for i=1,49 do
860 Zi = Zr*Zi*2 + Ci
861 Zr = Zrq-Ziq + Cr
862 Ziq = Zi*Zi
863 Zrq = Zr*Zr
864 if Zrq+Ziq > 4.0 then b = b + 1; break; end
865 end
866 if b >= 256 then p = p + 1; buf[p] = 511 - b; b = 1; end
867 end
868 if b ~= 1 then p = p + 1; buf[p] = (ba-b)*bb; end
869 result = result .. char(unpack(buf, 1, p))
870 end
871 return result
872 end
873 '''
874
875 image_size = 1280 # == 1280 x 1280
876 thread_count = 8
877
878 from lupa import LuaRuntime
879 lua_funcs = [ LuaRuntime(encoding=None).eval(lua_code)
880 for _ in range(thread_count) ]
881
882 results = [None] * thread_count
883 def mandelbrot(i, lua_func):
884 results[i] = lua_func(image_size, i+1, thread_count)
885
886 import threading
887 threads = [ threading.Thread(target=mandelbrot, args=(i,lua_func))
888 for i, lua_func in enumerate(lua_funcs) ]
889 for thread in threads:
890 thread.start()
891 for thread in threads:
892 thread.join()
893
894 result_buffer = b''.join(results)
895
896 # use Pillow to display the image
897 from PIL import Image
898 image = Image.frombytes('1', (image_size, image_size), result_buffer)
899 image.show()
900
901 Note how the example creates a separate ``LuaRuntime`` for each thread
902 to enable parallel execution. Each ``LuaRuntime`` is protected by a
903 global lock that prevents concurrent access to it. The low memory
904 footprint of Lua makes it reasonable to use multiple runtimes, but
905 this setup also means that values cannot easily be exchanged between
906 threads inside of Lua. They must either get copied through Python
907 space (passing table references will not work, either) or use some Lua
908 mechanism for explicit communication, such as a pipe or some kind of
909 shared memory setup.
910
911
912 Restricting Lua access to Python objects
913 ----------------------------------------
914
915 ..
916 >>> try: unicode = unicode
917 ... except NameError: unicode = str
918
919 Lupa provides a simple mechanism to control access to Python objects.
920 Each attribute access can be passed through a filter function as
921 follows:
922
923 .. code:: python
924
925 >>> def filter_attribute_access(obj, attr_name, is_setting):
926 ... if isinstance(attr_name, unicode):
927 ... if not attr_name.startswith('_'):
928 ... return attr_name
929 ... raise AttributeError('access denied')
930
931 >>> lua = lupa.LuaRuntime(
932 ... register_eval=False,
933 ... attribute_filter=filter_attribute_access)
934 >>> func = lua.eval('function(x) return x.__class__ end')
935 >>> func(lua)
936 Traceback (most recent call last):
937 ...
938 AttributeError: access denied
939
940 The ``is_setting`` flag indicates whether the attribute is being read
941 or set.
942
943 Note that the attributes of Python functions provide access to the
944 current ``globals()`` and therefore to the builtins etc. If you want
945 to safely restrict access to a known set of Python objects, it is best
946 to work with a whitelist of safe attribute names. One way to do that
947 could be to use a well selected list of dedicated API objects that you
948 provide to Lua code, and to only allow Python attribute access to the
949 set of public attribute/method names of these objects.
950
951 Since Lupa 1.0, you can alternatively provide dedicated getter and
952 setter function implementations for a ``LuaRuntime``:
953
954 .. code:: python
955
956 >>> def getter(obj, attr_name):
957 ... if attr_name == 'yes':
958 ... return getattr(obj, attr_name)
959 ... raise AttributeError(
960 ... 'not allowed to read attribute "%s"' % attr_name)
961
962 >>> def setter(obj, attr_name, value):
963 ... if attr_name == 'put':
964 ... setattr(obj, attr_name, value)
965 ... return
966 ... raise AttributeError(
967 ... 'not allowed to write attribute "%s"' % attr_name)
968
969 >>> class X(object):
970 ... yes = 123
971 ... put = 'abc'
972 ... noway = 2.1
973
974 >>> x = X()
975
976 >>> lua = lupa.LuaRuntime(attribute_handlers=(getter, setter))
977 >>> func = lua.eval('function(x) return x.yes end')
978 >>> func(x) # getting 'yes'
979 123
980 >>> func = lua.eval('function(x) x.put = "ABC"; end')
981 >>> func(x) # setting 'put'
982 >>> print(x.put)
983 ABC
984 >>> func = lua.eval('function(x) x.noway = 42; end')
985 >>> func(x) # setting 'noway'
986 Traceback (most recent call last):
987 ...
988 AttributeError: not allowed to write attribute "noway"
989
990
991 Restricting Lua Memory Usage
992 ----------------------------
993
994 Lupa provides a simple mechanism to control the maximum memory
995 usage of the Lua Runtime since version 2.0.
996 By default Lupa does not interfere with Lua's memory allocation, to opt-in
997 you must set the ``max_memory`` when creating the LuaRuntime.
998
999 The ``LuaRuntime`` provides three methods for controlling and reading the
1000 memory usage:
1001
1002 1. ``get_memory_used(total=False)`` to get the current memory
1003 usage of the LuaRuntime.
1004
1005 2. ``get_max_memory(total=False)`` to get the current memory limit.
1006 ``0`` means there is no memory limitation.
1007
1008 3. ``set_max_memory(max_memory, total=False)`` to change the memory limit.
1009 Values below or equal to 0 mean no limit.
1010
1011 There is always some memory used by the LuaRuntime itself (around ~20KiB,
1012 depending on your lua version and other factors) which is excluded from all
1013 calculations unless you specify ``total=True``.
1014
1015 .. code:: python
1016
1017 >>> from lupa import lua52
1018 >>> lua = lua52.LuaRuntime(max_memory=0) # 0 for unlimited, default is None
1019 >>> lua.get_memory_used() # memory used by your code
1020 0
1021 >>> total_lua_memory = lua.get_memory_used(total=True) # includes memory used by the runtime itself
1022 >>> assert total_lua_memory > 0 # exact amount depends on your lua version and other factors
1023
1024
1025 Lua code hitting the memory limit will receive memory errors:
1026
1027 .. code:: python
1028
1029 >>> lua.set_max_memory(100)
1030 >>> lua.eval("string.rep('a', 1000)") # doctest: +IGNORE_EXCEPTION_DETAIL
1031 Traceback (most recent call last):
1032 ...
1033 lupa.LuaMemoryError: not enough memory
1034
1035 ``LuaMemoryError`` inherits from ``LuaError`` and ``MemoryError``.
1036
1037
1038 Importing Lua binary modules
1039 ----------------------------
1040
1041 **This will usually work as is**, but here are the details, in case
1042 anything goes wrong for you.
1043
1044 To use binary modules in Lua, you need to compile them against the
1045 header files of the LuaJIT sources that you used to build Lupa, but do
1046 not link them against the LuaJIT library.
1047
1048 Furthermore, CPython needs to enable global symbol visibility for
1049 shared libraries before loading the Lupa module. This can be done by
1050 calling ``sys.setdlopenflags(flag_values)``. Importing the ``lupa``
1051 module will automatically try to set up the correct ``dlopen`` flags
1052 if it can find the platform specific ``DLFCN`` Python module that
1053 defines the necessary flag constants. In that case, using binary
1054 modules in Lua should work out of the box.
1055
1056 If this setup fails, however, you have to set the flags manually.
1057 When using the above configuration call, the argument ``flag_values``
1058 must represent the sum of your system's values for ``RTLD_NEW`` and
1059 ``RTLD_GLOBAL``. If ``RTLD_NEW`` is 2 and ``RTLD_GLOBAL`` is 256, you
1060 need to call ``sys.setdlopenflags(258)``.
1061
1062 Assuming that the Lua luaposix_ (``posix``) module is available, the
1063 following should work on a Linux system:
1064
1065 .. code:: python
1066
1067 >>> import sys
1068 >>> orig_dlflags = sys.getdlopenflags()
1069 >>> sys.setdlopenflags(258)
1070 >>> import lupa
1071 >>> sys.setdlopenflags(orig_dlflags)
1072
1073 >>> lua = lupa.LuaRuntime()
1074 >>> posix_module = lua.require('posix') # doctest: +SKIP
1075
1076 .. _luaposix: http://git.alpinelinux.org/cgit/luaposix
1077
1078
1079 Building with different Lua versions
1080 ------------------------------------
1081
1082 The build is configured to automatically search for an installed version
1083 of first LuaJIT and then Lua, and failing to find either, to use the bundled
1084 LuaJIT or Lua version.
1085
1086 If you wish to build Lupa with a specific version of Lua, you can
1087 configure the following options on setup:
1088
1089 .. list-table::
1090 :widths: 20 35
1091 :header-rows: 1
1092
1093 * - Option
1094 - Description
1095 * - ``--lua-lib <libfile>``
1096 - Lua library file path, e.g. ``--lua-lib /usr/local/lib/lualib.a``
1097 * - ``--lua-includes <incdir>``
1098 - Lua include directory, e.g. ``--lua-includes /usr/local/include``
1099 * - ``--use-bundle``
1100 - Use bundled LuaJIT or Lua instead of searching for an installed version.
1101 * - ``--no-bundle``
1102 - Don't use the bundled LuaJIT/Lua, search for an installed version of LuaJIT or Lua,
1103 e.g. using ``pkg-config``.
1104 * - ``--no-lua-jit``
1105 - Don't use or search for LuaJIT, only use or search Lua instead.
1106
1107
1108 Installing lupa
1109 ===============
1110
1111 Building with LuaJIT2
1112 ---------------------
1113
1114 #) Download and unpack lupa
1115
1116 http://pypi.python.org/pypi/lupa
1117
1118 #) Download LuaJIT2
1119
1120 http://luajit.org/download.html
1121
1122 #) Unpack the archive into the lupa base directory, e.g.::
1123
1124 .../lupa-0.1/LuaJIT-2.0.2
1125
1126 #) Build LuaJIT::
1127
1128 cd LuaJIT-2.0.2
1129 make
1130 cd ..
1131
1132 If you need specific C compiler flags, pass them to ``make`` as follows::
1133
1134 make CFLAGS="..."
1135
1136 For trickier target platforms like Windows and MacOS-X, please see
1137 the official `installation instructions for LuaJIT`_.
1138
1139 NOTE: When building on Windows, make sure that lua51.lib is made in addition
1140 to lua51.dll. The MSVC build produces this file, MinGW does NOT.
1141
1142 #) Build lupa::
1143
1144 python setup.py build_ext -i
1145
1146 Or any other distutils target of your choice, such as ``build``
1147 or one of the ``bdist`` targets. See the `distutils
1148 documentation`_ for help, also the `hints on building extension
1149 modules`_.
1150
1151 Note that on 64bit MacOS-X installations, the following additional
1152 compiler flags are reportedly required due to the embedded LuaJIT::
1153
1154 -pagezero_size 10000 -image_base 100000000
1155
1156 You can find additional installation hints for MacOS-X in this
1157 `somewhat unclear blog post`_, which may or may not tell you at
1158 which point in the installation process to provide these flags.
1159
1160 Also, on 64bit MacOS-X, you will typically have to set the
1161 environment variable ``ARCHFLAGS`` to make sure it only builds
1162 for your system instead of trying to generate a fat binary with
1163 both 32bit and 64bit support::
1164
1165 export ARCHFLAGS="-arch x86_64"
1166
1167 Note that this applies to both LuaJIT and Lupa, so make sure
1168 you try a clean build of everything if you forgot to set it
1169 initially.
1170
1171 .. _`installation instructions for LuaJIT`: http://luajit.org/install.html
1172 .. _`somewhat unclear blog post`: http://t-p-j.blogspot.com/2010/11/lupa-on-os-x-with-macports-python-26.html
1173 .. _`distutils documentation`: http://docs.python.org/install/index.html#install-index
1174 .. _`hints on building extension modules`: http://docs.python.org/install/index.html#building-extensions-tips-and-tricks
1175
1176
1177 Building with Lua 5.x
1178 ---------------------
1179
1180 It also works to use Lupa with the standard (non-JIT) Lua
1181 runtime. The easiest way is to use the bundled lua submodule:
1182
1183 #) Clone the submodule::
1184
1185 $ git submodule update --init third-party/lua
1186
1187 #) Build Lupa::
1188
1189 $ python3 setup.py bdist_wheel --use-bundle --with-cython
1190
1191 You can also build it by installing a Lua 5.x package, including
1192 any development packages (header files etc.). On systems that
1193 use the "pkg-config" configuration mechanism, Lupa's
1194 setup.py will pick up either LuaJIT2 or Lua automatically, with a
1195 preference for LuaJIT2 if it is found. Pass the ``--no-luajit`` option
1196 to the setup.py script if you have both installed but do not want to
1197 use LuaJIT2.
1198
1199 On other systems, you may have to supply the build parameters
1200 externally, e.g. using environment variables or by changing the
1201 setup.py script manually. Pass the ``--no-luajit`` option to the
1202 setup.py script in order to ignore the failure you get when neither
1203 LuaJIT2 nor Lua are found automatically.
1204
1205 For further information, read this mailing list post:
1206
1207 https://www.freelists.org/post/lupa-dev/Lupa-with-normal-Lua-interpreter-Lua-51,2
1208
1209
1210 Installing lupa from packages
1211 =============================
1212
1213 Debian/Ubuntu + Lua 5.2
1214 -----------------------
1215
1216 #) Install Lua 5.2 development package::
1217
1218 $ apt-get install liblua5.2-dev
1219
1220 #) Install lupa::
1221
1222 $ pip install lupa
1223
1224 Debian/Ubuntu + LuaJIT2
1225 -----------------------
1226
1227 #) Install LuaJIT2 development package::
1228
1229 $ apt-get install libluajit-5.1-dev
1230
1231 #) Install lupa::
1232
1233 $ pip install lupa
1234
1235 Depending on OS version, you might get an older LuaJIT2 version.
1236
1237 OS X + Lua 5.2 + Homebrew
1238 -------------------------
1239
1240 #) Install Lua::
1241
1242 $ brew install lua
1243
1244 #) Install pkg-config::
1245
1246 $ brew install pkg-config
1247
1248 #) Install lupa::
1249
1250 $ pip install lupa
1251
1252
1253 Lupa change log
1254 ===============
1255
1256 2.4 (2025-01-10)
1257 ----------------
1258
1259 * The windows wheels now bundle LuaJIT 2.0 and 2.1.
1260 (patch by Michal Plichta)
1261
1262 * Failures in the test suite didn't set a non-zero process exit value.
1263
1264
1265 2.3 (2025-01-09)
1266 ----------------
1267
1268 * The bundled LuaJIT versions were updated to the latest git branches.
1269
1270 * The bundled Lua 5.4 was updated to 5.4.7.
1271
1272 * Removed support for Python 2.x.
1273
1274 * Built with Cython 3.0.11.
1275
1276
1277 2.2 (2024-06-02)
1278 ----------------
1279
1280 * A new method ``LuaRuntime.gccollect()`` was added to trigger the Lua garbage collector.
1281
1282 * A new context manager ``LuaRuntime.nogc()`` was added to temporarily disable the Lua
1283 garbage collector.
1284
1285 * Freeing Python objects from a thread while running Lua code could run into a deadlock.
1286
1287 * The bundled LuaJIT versions were updated to the latest git branches.
1288
1289 * Built with Cython 3.0.10.
1290
1291
1292 2.1 (2024-03-24)
1293 ----------------
1294
1295 * GH#199: The ``table_from()`` method gained a new keyword argument ``recursive=False``.
1296 If true, Python data structures will be recursively mapped to Lua tables,
1297 taking care of loops and duplicates via identity de-duplication.
1298
1299 * GH#248: The LuaRuntime methods "eval", "execute" and "compile" gained new
1300 keyword options ``mode`` and ``name`` that allow constraining the input type
1301 and modifying the (chunk) name shown in error messages, following similar
1302 arguments in the Lua ``load()`` function.
1303 See https://www.lua.org/manual/5.4/manual.html#pdf-load
1304
1305 * GH#246: Loading Lua modules did not work for the version specific Lua modules
1306 introduced in Lupa 2.0. It turned out that it can only be enabled for
1307 one of them in a given Python run, so it is now left to users to enable it
1308 explicitly at need.
1309 (original patch by Richard Connon)
1310
1311 * GH#234: The bundled Lua 5.1 was updated to 5.1.5 and Lua 5.2 to 5.2.4.
1312 (patch by xxyzz)
1313
1314 * The bundled Lua 5.4 was updated to 5.4.6.
1315
1316 * The bundled LuaJIT versions were updated to the latest git branches.
1317
1318 * Built with Cython 3.0.9 for improved support of Python 3.12/13.
1319
1320
1321 2.0 (2023-04-03)
1322 ----------------
1323
1324 * GH#217: Lua stack traces in Python exception messages are now reversed to
1325 match the order of Python stack traces.
1326
1327 * GH#196: Lupa now ships separate extension modules built with Lua 5.3,
1328 Lua 5.4, LuaJIT 2.0 and LuaJIT 2.1 beta. Note that this is build specific
1329 and may depend on the platform. A normal Python import cascade can be used.
1330
1331 * GH#211: A new option `max_memory` allows to limit the memory usage of Lua code.
1332 (patch by Leo Developer)
1333
1334 * GH#171: Python references in Lua are now more safely reference counted
1335 to prevent garbage collection glitches.
1336 (patch by Guilherme Dantas)
1337
1338 * GH#146: Lua integers in Lua 5.3+ are converted from and to Python integers.
1339 (patch by Guilherme Dantas)
1340
1341 * GH#180: The ``python.enumerate()`` function now returns indices as integers
1342 if supported by Lua.
1343 (patch by Guilherme Dantas)
1344
1345 * GH#178: The Lua integer limits can be read from the module as
1346 ``LUA_MAXINTEGER`` and ``LUA_MININTEGER``.
1347 (patch by Guilherme Dantas)
1348
1349 * GH#174: Failures while calling the ``__index`` method in Lua during a
1350 table index lookup from Python could crash Python.
1351 (patch by Guilherme Dantas)
1352
1353 * GH#137: Passing ``None`` as a dict key into ``table_from()`` crashed.
1354 (patch by Leo Developer)
1355
1356 * GH#176: A new function ``python.args(*args, **kwargs)`` was added
1357 to help with building Python argument tuples and keyword argument dicts
1358 for Python function calls from Lua code.
1359
1360 * GH#177: Tables that are not sequences raise ``IndexError`` when unpacking
1361 them. Previously, non-sequential items were simply ignored.
1362
1363 * GH#179: Resolve some C compiler warnings about signed/unsigned comparisons.
1364 (patch by Guilherme Dantas)
1365
1366 * Built with Cython 0.29.34.
1367
1368
1369 1.14.1 (2022-11-16)
1370 -------------------
1371
1372 * Rebuild with Cython 0.29.32 to support Python 3.11.
1373
1374
1375 1.13 (2022-03-01)
1376 -----------------
1377
1378 * Bundled Lua source files were missing in the source distribution.
1379
1380
1381 1.12 (2022-02-24)
1382 -----------------
1383
1384 * GH#197: Some binary wheels in the last releases were not correctly linked with Lua.
1385
1386 * GH#194: An absolute file path appeared in the ``SOURCES.txt`` metadata
1387 of the source distribution.
1388
1389
1390 1.11 (2022-02-23)
1391 -----------------
1392
1393 * Use Lua 5.4.4 in binary wheels and as bundled Lua.
1394
1395 * Built with Cython 0.29.28 to support Python 3.10/11.
1396
1397
1398 1.10 (2021-09-02)
1399 -----------------
1400
1401 * GH#147: Lua 5.4 is supported.
1402 (patch by Russel Davis)
1403
1404 * The runtime version of the Lua library as a tuple (e.g. ``(5,3)``)
1405 is provided via ``lupa.LUA_VERSION`` and ``LuaRuntime.lua_version``.
1406
1407 * The Lua implementation name and version string is provided as
1408 ``LuaRuntime.lua_implementation``.
1409
1410 * ``setup.py`` accepts new command line arguments ``--lua-lib`` and ``--lua-includes``
1411 to specify the
1412
1413 * Use Lua 5.4.3 in binary wheels and as bundled Lua.
1414
1415 * Built with Cython 0.29.24 to support Python 3.9.
1416
1417
1418 1.9 (2019-12-21)
1419 ----------------
1420
1421 * Build against Lua 5.3 if available.
1422
1423 * Use Lua 5.3.5 in binary wheels and as bundled Lua.
1424
1425 * GH#129: Fix Lua module loading in Python 3.x.
1426
1427 * GH#126: Fix build on Linux systems that install Lua as "lua52" package.
1428
1429 * Built with Cython 0.29.14 for better Py3.8 compatibility.
1430
1431
1432 1.8 (2019-02-01)
1433 ----------------
1434
1435 * GH#107: Fix a deprecated import in Py3.
1436
1437 * Built with Cython 0.29.3 for better Py3.7 compatibility.
1438
1439
1440 1.7 (2018-08-06)
1441 ----------------
1442
1443 * GH#103: Provide wheels for MS Windows and fix MSVC build on Py2.7.
1444
1445
1446 1.6 (2017-12-15)
1447 ----------------
1448
1449 * GH#95: Improved compatibility with Lua 5.3.
1450 (patch by TitanSnow)
1451
1452
1453 1.5 (2017-09-16)
1454 ----------------
1455
1456 * GH#93: New method ``LuaRuntime.compile()`` to compile Lua code
1457 without executing it.
1458 (patch by TitanSnow)
1459
1460 * GH#91: Lua 5.3 is bundled in the source distribution to simplify
1461 one-shot installs.
1462 (patch by TitanSnow)
1463
1464 * GH#87: Lua stack trace is included in output in debug mode.
1465 (patch by aaiyer)
1466
1467 * GH#78: Allow Lua code to intercept Python exceptions.
1468 (patch by Sergey Dobrov)
1469
1470 * Built with Cython 0.26.1.
1471
1472
1473 1.4 (2016-12-10)
1474 ----------------
1475
1476 * GH#82: Lua coroutines were using the wrong runtime state
1477 (patch by Sergey Dobrov)
1478
1479 * GH#81: copy locally provided Lua DLL into installed package on Windows
1480 (patch by Gareth Coles)
1481
1482 * built with Cython 0.25.2
1483
1484
1485 1.3 (2016-04-12)
1486 ----------------
1487
1488 * GH#70: ``eval()`` and ``execute()`` accept optional positional arguments
1489 (patch by John Vandenberg)
1490
1491 * GH#65: calling ``str()`` on a Python object from Lua could fail if the
1492 ``LuaRuntime`` is set up without auto-encoding (patch by Mikhail Korobov)
1493
1494 * GH#63: attribute/keyword names were not properly encoded if the
1495 ``LuaRuntime`` is set up without auto-encoding (patch by Mikhail Korobov)
1496
1497 * built with Cython 0.24
1498
1499
1500 1.2 (2015-10-10)
1501 ----------------
1502
1503 * callbacks returned from Lua coroutines were incorrectly mixing
1504 coroutine state with global Lua state (patch by Mikhail Korobov)
1505
1506 * availability of ``python.builtins`` in Lua can be disabled via
1507 ``LuaRuntime`` option.
1508
1509 * built with Cython 0.23.4
1510
1511
1512 1.1 (2014-11-21)
1513 ----------------
1514
1515 * new module function ``lupa.lua_type()`` that returns the Lua type of
1516 a wrapped object as string, or ``None`` for normal Python objects
1517
1518 * new helper method ``LuaRuntime.table_from(...)`` that creates a Lua
1519 table from one or more Python mappings and/or sequences
1520
1521 * new ``lupa.unpacks_lua_table`` and ``lupa.unpacks_lua_table_method``
1522 decorators to allow calling Python functions from Lua using named
1523 arguments
1524
1525 * fix a hang on shutdown where the LuaRuntime failed to deallocate due
1526 to reference cycles
1527
1528 * Lupa now plays more nicely with other Lua extensions that create
1529 userdata objects
1530
1531
1532 1.0.1 (2014-10-11)
1533 ------------------
1534
1535 * fix a crash when requesting attributes of wrapped Lua coroutine objects
1536
1537 * looking up attributes on Lua objects that do not support it now always
1538 raises an AttributeError instead of sometimes raising a TypeError depending
1539 on the attribute name
1540
1541
1542 1.0 (2014-09-28)
1543 ----------------
1544
1545 * NOTE: this release includes the major backwards incompatible changes listed
1546 below. It is believed that they simplify the interaction between Python code
1547 and Lua code by more strongly following idiomatic Lua on the Lua side.
1548
1549 * Instead of passing a wrapped ``python.none`` object into Lua, ``None``
1550 return values are now mapped to ``nil``, making them more straight forward
1551 to handle in Lua code. This makes the behaviour more consistent, as it
1552 was previously somewhat arbitrary where ``none`` could appear and where a
1553 ``nil`` value was used. The only remaining exception is during iteration,
1554 where the first returned value must not be ``nil`` in Lua, or otherwise
1555 the loop terminates prematurely. To prevent this, any ``None`` value
1556 that the iterator returns, or any first item in exploded tuples that is
1557 ``None``, is still mapped to ``python.none``. Any further values
1558 returned in the same iteration will be mapped to ``nil`` if they are
1559 ``None``, not to ``none``. This means that only the first argument
1560 needs to be manually checked for this special case. For the
1561 ``enumerate()`` iterator, the counter is never ``None`` and thus the
1562 following unpacked items will never be mapped to ``python.none``.
1563
1564 * When ``unpack_returned_tuples=True``, iteration now also unpacks tuple
1565 values, including ``enumerate()`` iteration, which yields a flat sequence
1566 of counter and unpacked values.
1567
1568 * When calling bound Python methods from Lua as "obj:meth()", Lupa now
1569 prevents Python from prepending the self argument a second time, so that
1570 the Python method is now called as "obj.meth()". Previously, it was called
1571 as "obj.meth(obj)". Note that this can be undesired when the object itself
1572 is explicitly passed as first argument from Lua, e.g. when calling
1573 "func(obj)" where "func" is "obj.meth", but these constellations should be
1574 rare. As a work-around for this case, user code can wrap the bound method
1575 in another function so that the final call comes from Python.
1576
1577 * garbage collection works for reference cycles that span both runtimes,
1578 Python and Lua
1579
1580 * calling from Python into Lua and back into Python did not clean up the
1581 Lua call arguments before the innermost call, so that they could leak
1582 into the nested Python call or its return arguments
1583
1584 * support for Lua 5.2 (in addition to Lua 5.1 and LuaJIT 2.0)
1585
1586 * Lua tables support Python's "del" statement for item deletion
1587 (patch by Jason Fried)
1588
1589 * Attribute lookup can use a more fine-grained control mechanism by
1590 implementing explicit getter and setter functions for a LuaRuntime
1591 (``attribute_handlers`` argument). Patch by Brian Moe.
1592
1593 * item assignments/lookups on Lua objects from Python no longer
1594 special case double underscore names (as opposed to attribute lookups)
1595
1596
1597 0.21 (2014-02-12)
1598 -----------------
1599
1600 * some garbage collection issues were cleaned up using new Cython features
1601
1602 * new ``LuaRuntime`` option ``unpack_returned_tuples`` which automatically
1603 unpacks tuples returned from Python functions into separate Lua objects
1604 (instead of returning a single Python tuple object)
1605
1606 * some internal wrapper classes were removed from the module API
1607
1608 * Windows build fixes
1609
1610 * Py3.x build fixes
1611
1612 * support for building with Lua 5.1 instead of LuaJIT (setup.py --no-luajit)
1613
1614 * no longer uses Cython by default when building from released sources (pass
1615 ``--with-cython`` to explicitly request a rebuild)
1616
1617 * requires Cython 0.20+ when building from unreleased sources
1618
1619 * built with Cython 0.20.1
1620
1621
1622 0.20 (2011-05-22)
1623 -----------------
1624
1625 * fix "deallocating None" crash while iterating over Lua tables in
1626 Python code
1627
1628 * support for filtering attribute access to Python objects for Lua
1629 code
1630
1631 * fix: setting source encoding for Lua code was broken
1632
1633
1634 0.19 (2011-03-06)
1635 -----------------
1636
1637 * fix serious resource leak when creating multiple LuaRuntime instances
1638
1639 * portability fix for binary module importing
1640
1641
1642 0.18 (2010-11-06)
1643 -----------------
1644
1645 * fix iteration by returning ``Py_None`` object for ``None`` instead
1646 of ``nil``, which would terminate the iteration
1647
1648 * when converting Python values to Lua, represent ``None`` as a
1649 ``Py_None`` object in places where ``nil`` has a special meaning,
1650 but leave it as ``nil`` where it doesn't hurt
1651
1652 * support for counter start value in ``python.enumerate()``
1653
1654 * native implementation for ``python.enumerate()`` that is several
1655 times faster
1656
1657 * much faster Lua iteration over Python objects
1658
1659
1660 0.17 (2010-11-05)
1661 -----------------
1662
1663 * new helper function ``python.enumerate()`` in Lua that returns a Lua
1664 iterator for a Python object and adds the 0-based index to each
1665 item.
1666
1667 * new helper function ``python.iterex()`` in Lua that returns a Lua
1668 iterator for a Python object and unpacks any tuples that the
1669 iterator yields.
1670
1671 * new helper function ``python.iter()`` in Lua that returns a Lua
1672 iterator for a Python object.
1673
1674 * reestablished the ``python.as_function()`` helper function for Lua
1675 code as it can be needed in cases where Lua cannot determine how to
1676 run a Python function.
1677
1678
1679 0.16 (2010-09-03)
1680 -----------------
1681
1682 * dropped ``python.as_function()`` helper function for Lua as all
1683 Python objects are callable from Lua now (potentially raising a
1684 ``TypeError`` at call time if they are not callable)
1685
1686 * fix regression in 0.13 and later where ordinary Lua functions failed
1687 to print due to an accidentally used meta table
1688
1689 * fix crash when calling ``str()`` on wrapped Lua objects without
1690 metatable
1691
1692
1693 0.15 (2010-09-02)
1694 -----------------
1695
1696 * support for loading binary Lua modules on systems that support it
1697
1698
1699 0.14 (2010-08-31)
1700 -----------------
1701
1702 * relicensed to the MIT license used by LuaJIT2 to simplify licensing
1703 considerations
1704
1705
1706 0.13.1 (2010-08-30)
1707 -------------------
1708
1709 * fix Cython generated C file using Cython 0.13
1710
1711
1712 0.13 (2010-08-29)
1713 -----------------
1714
1715 * fixed undefined behaviour on ``str(lua_object)`` when the object's
1716 ``__tostring()`` meta method fails
1717
1718 * removed redundant "error:" prefix from ``LuaError`` messages
1719
1720 * access to Python's ``python.builtins`` from Lua code
1721
1722 * more generic wrapping rules for Python objects based on supported
1723 protocols (callable, getitem, getattr)
1724
1725 * new helper functions ``as_attrgetter()`` and ``as_itemgetter()`` to
1726 specify the Python object protocol used by Lua indexing when
1727 wrapping Python objects in Python code
1728
1729 * new helper functions ``python.as_attrgetter()``,
1730 ``python.as_itemgetter()`` and ``python.as_function()`` to specify
1731 the Python object protocol used by Lua indexing of Python objects in
1732 Lua code
1733
1734 * item and attribute access for Python objects from Lua code
1735
1736
1737 0.12 (2010-08-16)
1738 -----------------
1739
1740 * fix Lua stack leak during table iteration
1741
1742 * fix lost Lua object reference after iteration
1743
1744
1745 0.11 (2010-08-07)
1746 -----------------
1747
1748 * error reporting on Lua syntax errors failed to clean up the stack so
1749 that errors could leak into the next Lua run
1750
1751 * Lua error messages were not properly decoded
1752
1753
1754 0.10 (2010-07-27)
1755 -----------------
1756
1757 * much faster locking of the LuaRuntime, especially in the single
1758 threaded case (see
1759 http://code.activestate.com/recipes/577336-fast-re-entrant-optimistic-lock-implemented-in-cyt/)
1760
1761 * fixed several error handling problems when executing Python code
1762 inside of Lua
1763
1764
1765 0.9 (2010-07-23)
1766 ----------------
1767
1768 * fixed Python special double-underscore method access on LuaObject
1769 instances
1770
1771 * Lua coroutine support through dedicated wrapper classes, including
1772 Python iteration support. In Python space, Lua coroutines behave
1773 exactly like Python generators.
1774
1775
1776 0.8 (2010-07-21)
1777 ----------------
1778
1779 * support for returning multiple values from Lua evaluation
1780
1781 * ``repr()`` support for Lua objects
1782
1783 * ``LuaRuntime.table()`` method for creating Lua tables from Python
1784 space
1785
1786 * encoding fix for ``str(LuaObject)``
1787
1788
1789 0.7 (2010-07-18)
1790 ----------------
1791
1792 * ``LuaRuntime.require()`` and ``LuaRuntime.globals()`` methods
1793
1794 * renamed ``LuaRuntime.run()`` to ``LuaRuntime.execute()``
1795
1796 * support for ``len()``, ``setattr()`` and subscripting of Lua objects
1797
1798 * provide all built-in Lua libraries in ``LuaRuntime``, including
1799 support for library loading
1800
1801 * fixed a thread locking issue
1802
1803 * fix passing Lua objects back into the runtime from Python space
1804
1805
1806 0.6 (2010-07-18)
1807 ----------------
1808
1809 * Python iteration support for Lua objects (e.g. tables)
1810
1811 * threading fixes
1812
1813 * fix compile warnings
1814
1815
1816 0.5 (2010-07-14)
1817 ----------------
1818
1819 * explicit encoding options per LuaRuntime instance to decode/encode
1820 strings and Lua code
1821
1822
1823 0.4 (2010-07-14)
1824 ----------------
1825
1826 * attribute read access on Lua objects, e.g. to read Lua table values
1827 from Python
1828
1829 * str() on Lua objects
1830
1831 * include .hg repository in source downloads
1832
1833 * added missing files to source distribution
1834
1835
1836 0.3 (2010-07-13)
1837 ----------------
1838
1839 * fix several threading issues
1840
1841 * safely free the GIL when calling into Lua
1842
1843
1844 0.2 (2010-07-13)
1845 ----------------
1846
1847 * propagate Python exceptions through Lua calls
1848
1849
1850 0.1 (2010-07-12)
1851 ----------------
1852
1853 * first public release
1854
1855
1856 License
1857 =======
1858
1859 Lupa
1860 ----
1861
1862 Copyright (c) 2010-2017 Stefan Behnel. All rights reserved.
1863
1864 Permission is hereby granted, free of charge, to any person obtaining a copy
1865 of this software and associated documentation files (the "Software"), to deal
1866 in the Software without restriction, including without limitation the rights
1867 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
1868 copies of the Software, and to permit persons to whom the Software is
1869 furnished to do so, subject to the following conditions:
1870
1871 The above copyright notice and this permission notice shall be included in
1872 all copies or substantial portions of the Software.
1873
1874 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1875 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1876 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1877 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1878 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
1879 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
1880 THE SOFTWARE.
1881
1882 Lua
1883 ---
1884
1885 (See https://www.lua.org/license.html)
1886
1887 Copyright © 1994–2017 Lua.org, PUC-Rio.
1888
1889 Permission is hereby granted, free of charge, to any person obtaining a copy
1890 of this software and associated documentation files (the "Software"), to deal
1891 in the Software without restriction, including without limitation the rights
1892 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
1893 copies of the Software, and to permit persons to whom the Software is
1894 furnished to do so, subject to the following conditions:
1895
1896 The above copyright notice and this permission notice shall be included in
1897 all copies or substantial portions of the Software.
1898
1899 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1900 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1901 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1902 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1903 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
1904 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
1905 THE SOFTWARE.