Python

来源:互联网 发布:即时通讯软件市场份额 编辑:程序博客网 时间:2024/06/16 19:10

Python 调用Lua

lupa将Lua和LuaJIT2集成进CPython,可以在Python中执行Lua代码.

Lupa的主要特点:
- separate Lua runtime states through a LuaRuntime class
- Python coroutine wrapper for Lua coroutines
- iteration support for Python objects in Lua and Lua objects in Python
- proper encoding and decoding of strings (configurable per runtime, UTF-8 by default)
- frees the GIL and supports threading in separate runtimes when calling into Lua解决了GIL问题,支持多线程
- tested with Python 2.6/3.2 and later 适用于Python 2.6/3.2以后的版本
- written for LuaJIT2 (tested with LuaJIT 2.0.2), but also works with the normal Lua interpreter (5.1 and 5.2)
- easy to hack on and extend as it is written in Cython, not C 扩展性好

1. lupa安装

这里基于Ubuntu14.04.
lupa官网提供的教程:

# ForDebian/Ubuntu + Lua 5.2sudo apt-get install liblua5.2-dev  # Install Lua 5.2 development packagesudo pip install lupa  # Install lupa# For Debian/Ubuntu + LuaJIT2sudo apt-get install libluajit-5.1-dev  # Install LuaJIT2 development packagesudo pip install lupa  # Install lupa

源码安装方式如下:

1.1 安装lua环境

curl -R -O http://www.lua.org/ftp/lua-5.3.4.tar.gztar zxf lua-5.3.4.tar.gzcd lua-5.3.4make linux testmake install

注:如果遇到错误:fatal error: readline/readline.h: No such file or directory,则需要安装readline-dev

sudo apt-get install libreadline-dev

测试是否安装成功:
新建 hellolua.lua脚本,代码如下:

print("Hello Lua!")

执行命令:

lua hellolua.lua

安装成功,则输出:

Hello Lua!

1.2 安装LuaJIT

wget -c http://luajit.org/download/LuaJIT-2.0.5.tar.gztar zxf LuaJIT-2.0.5.tar.gzcd LuaJIT-2.0.5sudo make install PREFIX=/usr/local/luajitecho "/usr/local/luajit/lib" > /etc/ld.so.conf.d/usr_local_luajit_lib.confsudo ldconfigexport LUAJIT_LIB=/usr/local/luajit/libexport LUAJIT_INC=/usr/local/luajit/include/luajit-2.0

1.3 lupa安装

sudo pip install lupa

2. 实例

基本用法

import lupafrom lupa import LuaRuntimelua = LuaRuntime(unpack_returned_tuples=True)lua.eval('1+1') # output: 2lua_func = lua.eval('function(f, n) return f(n) end')def py_add1(n):     return n+1lua_func(py_add1, 2) # output: 3lua.eval('python.eval(" 2 ** 2 ")') == 4 # output: Truelua.eval('python.builtins.str(4)') == '4' # output: True# lua_type(obj) 函数用于输出 type of a wrapped Lua objectlupa.lua_type(lua_func) # output: 'function'lupa.lua_type(lua.eval('{}')) # output: 'table'lupa.lua_type(123) is None # output: Truelupa.lua_type('abc') is None # output: Truelupa.lua_type({}) is None # output: True# flag unpack_returned_tuples=True that is passed to create the Lua runtimelua.execute('a,b,c = python.eval("(1,2)")')g = lua.globals()g.a   # output: 1g.b   # output: 2g.c is None   # output: True# flag unpack_returned_tuples=False, functions that return a tuple pass it through to the Lua codenon_explode_lua = lupa.LuaRuntime(unpack_returned_tuples=False)non_explode_lua.execute('a,b,c = python.eval("(1,2)")')g = non_explode_lua.globals()g.a   # output: (1, 2)g.b is None  # output: Trueg.c is None  # output: True

更多用法参考lupa官网.

原创粉丝点击