标签:
如果有一段lua脚本代码, 本来来源不可靠, 可能有安全性问题, 或者不像让这份代码污染了正在执行的lua环境, 则需要lua rings工具出厂了。
其在主lua环境中,即在宿主脚本中, 调用rings库创建一个子的lua环境, 将不可靠的lua代码在子lua环境中运行, 运行完毕环境销毁, 一点都不影响宿主环境。
Rings is a library which provides a way to create new Lua states from within Lua. It also offers a simple way to communicate between the creator (master) and the created (slave) states.
官网介绍,有帮助文档:
http://keplerproject.github.io/rings/manual.html
git hub可以下载最新源代码:
https://github.com/keplerproject/rings
基本接口
- rings.new (env) --- 创建一个lua环境
- Returns a newly created Lua state. Takes an optional environment to be used by
remotedostring
. If the environment is nil, it defaults to the master_M or _G
tables.- state:close () --- 销毁创建的lua环境
- Closes the state.
- state:dostring (string, ...) ---- 在lua环境中执行一段lua代码
- Executes a string in the slave state. The arguments could be accessed exactly as in a vararg function. Valid types of arguments and return values are: number, string, boolean, nil and userdata (which are converted to lightuserdata).
Returns a boolean indicating the status of the operation, followed by the returned values or an error message in case of error.
此插件还考虑到, 子环境如何存储 数据, 保证与宿主环境可以交换数据:
Stable
Stable is a simple API which provides a way for a slave state to store and retrieve data to and from its master state. This library is not opened automatically in a slave state.
参考其源代码中最简单的例子sample.lua
- $Id: sample.lua,v 1.4 2008/05/30 18:44:05 carregal Exp $ require"rings" S = rings.new () data = { 12, 13, 14, } print (S:dostring ([[ aux = {} for i, v in ipairs {...} do table.insert (aux, 1, v) end return unpack (aux)]], unpack (data)))
-- 主要在此处说明, 子环境不会污染宿主环境, 同时说明了 宿主环境中执行不可靠代码, 将会污染宿主环境自身 if nil == aux then print("aux do not exist in Global Environment!"); f = loadstring([[ aux = {1} ]]) print(f()) --> do lua code print("after call global dostring, aux created, aux[0]=="..aux[1]); end S:close () print("OK!") ~
实验结果:
xx:~/share_windows/openSource/lua/rings-master/tests$ lua sample.lua
true 14 13 12
aux do not exist in Global Environment!
after call global dostring, aux created, aux[0]==1
OK!
标签:
原文地址:http://www.cnblogs.com/lightsong/p/4601280.html