地址:http://www.cnblogs.com/coderzh/archive/2010/11/29/lupa.html
PS:刚刚才发现Arduino中可以直接运行lua脚本,嘻嘻这个是个更好的进一步学习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_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
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
... 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)
[1, 2, 3, 4]>>> list(table.values())
[10, 20, 30, 40]>>> 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)
[-3, 3, 20]>>> sorted(mapping.items())
[(-3, 3), (3, -3), (20, -20)]
>>> table[4]40
>>> list(table)
[1, 2, 3, 4]>>> list(table.values())
[10, 20, 30, 40]>>> 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)
[-3, 3, 20]>>> sorted(mapping.items())
[(-3, 3), (3, -3), (20, -20)]
(等等……)
没有评论:
发表评论