Lupa Python中调用Lua

Lupa将LuaJIT集成到了Python模块中,可以在Python中执行Lua代码。 比较有意思,也许以后用的着,记录一下。

基本用法:

>>> import lupa
>>> from lupa import LuaRuntime
>>> lua = LuaRuntime()

>>> lua.eval('1+1')
2

>>> lua_func = lua.eval('function(f, n) return f(n) end')

>>> def py_add1(n): return n+1
>>> lua_func(py_add1, 2)
3

>>> lua.eval('python.eval(" 2 ** 2 ")'== 4
True
>>> lua.eval('python.builtins.str(4)'== '4'
True


Lua中的Python对象 

>>> lua_func = lua.eval('function(obj) return obj["get"] end')
>>> d = {'get' : 'got'}

>>> value = lua_func(d)
>>> value == 'got'
True

>>> dict_get = lua_func( lupa.as_attrgetter(d) )
>>> dict_get('get'== 'got'
True

>>> lua_func = lua.eval(
...     
'function(obj) return python.as_attrgetter(obj)["get"] end')
>>> dict_get = lua_func(d)
>>> dict_get('get'== 'got'
True


Lua中的迭代循环:

>>> lua_copy = lua.eval('''
...     function(L)
...         local t, i = {}, 1
...         for item in python.iter(L) do
...             t[i] = item
...             i = i + 1
...         end
...         return t
...     end
... 
''')

>>> table = lua_copy([1,2,3,4])
>>> len(table)
4
>>> table[1]   # Lua indexing
1


Lua中的Table:

>>> table = lua.eval('{10,20,30,40}')
>>> table[1]
10
>>> table[4]
40
>>> list(table)
[
1234]
>>> list(table.values())
[
10203040]
>>> len(table)
4

>>> mapping = lua.eval('{ [1] = -1 }')
>>> list(mapping)
[
1]

>>> mapping = lua.eval('{ [20] = -20; [3] = -3 }')
>>> mapping[20]
-20
>>> mapping[3]
-3
>>> sorted(mapping.values())
[
-20-3]
>>> sorted(mapping.items())
[(
3-3), (20-20)]

>>> mapping[-3= 3     # -3 used as key, not index!
>>> mapping[-3]
3
>>> sorted(mapping)
[
-3320]
>>> sorted(mapping.items())
[(
-33), (3-3), (20-20)]


(等等……)

参考:

1. http://pypi.python.org/pypi/lupa/0.18

2. http://androguard.blogspot.com/2010/11/lupa-lua-from-python.html

微信扫一扫交流

作者:CoderZh
公众号:hacker-thinking (一个程序员的思考)
独立博客:http://blog.coderzh.com
博客园博客将不再更新,请关注我的「微信公众号」或「独立博客」。
作为一个程序员,思考程序的每一行代码,思考生活的每一个细节,思考人生的每一种可能。
文章版权归本人所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

原文地址:https://www.cnblogs.com/coderzh/p/lupa.html