一、引言
上一周有某個特殊需求,需要在伺服器端搭建一個lua執行環境。lua本身又是嵌入語言。在語言本身上又一定的局限性。是以我打算把lua嵌入到python/java中。做調研的時候,java的嵌入較為麻煩,出現了各種問題。後來确定用python來作這個環境。這樣能用上python 的協程、多線程。這裡說說python中嵌入lua的問題。
二、環境建立
python中又一個擴充叫lupa。這個擴充用于在python中嵌入lua。安裝
pip install lupa
我隻在liunx/oxs中安裝過。在liunx上一下就成功了。oxs上出了些問題。可以google出來。
三、例子
在兩個線程中執行lua腳本。這裡需要兩個檔案test.lua與test.py.
1.test.lua
-- User:rudy
-- Time:2016/07/15
function test1(params)
return 'test1:'..params
end
function test2(params)
return 'test2:'..params
end
-- 入口函數,實作反射函數調用
function functionCall(func_name,params)
local is_true,result
local sandBox = function(func_name,params)
local result
result = _G[func_name](params)
return result
end
is_true,result= pcall(sandBox,func_name,params)
return result
end
在這個檔案中定義了三個函數,test1,test2為測試函數。functionCall用于實作統一的函數調用方式。
2.test.py
# -*-coding:utf-8-*-
import traceback
from lupa import LuaRuntime
import threading
class Executor(threading.Thread):
"""
執行lua的線程類
"""
lock = threading.RLock()
luaScriptContent = None
luaRuntime = None
def __init__(self,api,params):
threading.Thread.__init__(self)
self.params = params
self.api = api
def run(self):
try:
# 執行具體的函數,傳回結果列印在螢幕上
luaRuntime = self.getLuaRuntime()
rel = luaRuntime(self.api, self.params)
print rel
except Exception,e:
print e.message
traceback.extract_stack()
def getLuaRuntime(self):
"""
從檔案中加載要執行的lua腳本,初始化lua執行環境
"""
# 上鎖,保證多個線程加載不會沖突
if Executor.lock.acquire():
if Executor.luaRuntime is None:
fileHandler = open('./test.lua')
content = ''
try:
content = fileHandler.read()
except Exception, e:
print e.message
traceback.extract_stack()
# 建立lua執行環境
Executor.luaScriptContent = content
luaRuntime = LuaRuntime()
luaRuntime.execute(content)
# 從lua執行環境中取出全局函數functionCall作為入口函數調用,實作lua的反射調用
g = luaRuntime.globals()
function_call = g.functionCall
Executor.luaRuntime = function_call
Executor.lock.release()
return Executor.luaRuntime
if __name__ == "__main__":
# 在兩個線程中分别執行lua中test1,test2函數
executor1 = Executor('test1','hello world')
executor2 = Executor('test2','rudy')
executor1.start()
executor2.start()
executor1.join()
executor2.join()
這個檔案中定義了lua執行線程類。用于具體執行lua代碼。具體作用參見代碼注釋。
3.執行結果
如圖
圖1.python嵌入lua執行結果