Thursday, November 18, 2010

Lupa : Lua from Python !

Hi !

I was testing to invoke lua from python, to test some piece of codes. So I started to create a binding after (;() but I found LUPA !

An archive and installation is described in the web page. You can test it by importing the module :
>>> import lupa
>>> x = lupa.LuaRuntime()
>>> x.eval( "print \"hello\" ")
hello
>>>
I would like to do object-oriented programming directly in my python code with lupa, but I failed (maybe I'm wrong). So I did it a simple wrapper in python :
lua_code_init = '''
TEST = {}
function TEST:new()
o = {}
setmetatable(o, self)
self.__index = self
return o
end

function TEST:affect(v)
print("affect |----> " .. v)
self.value = v
end

function TEST:OP(arg)
for item in python.iter(arg) do
print(item)
end
end

return TEST
'''

class LuaFunc :
def __init__(self, function, obj) :
self.__function = function
self.__obj = obj

def __call__(self, *args, **kwargs):
nargs = [self.__obj]
nargs.extend(args)
return apply(self.__function, nargs, kwargs)

class LuaObject :
def __init__(self, obj) :
self.__obj = obj

self.__dict__[ "affect" ] = LuaFunc( self.__obj.affect, self.__obj )
self.__dict__[ "OP" ] = LuaFunc( self.__obj.OP, self.__obj )

class LuaClass :
def __init__(self, lua, init) :
self.__lua = lua
self.__class = self.__lua.execute( init )

self.__obj = LuaObject( self.__class.new(self.__class) )

def get_obj(self) :
return self.__obj

def __getattr__(self, *args, **kwargs) :
return getattr(self.__obj, *args)
So now I can do stuff like that :
lua = lupa.LuaRuntime()
o = LuaClass(lua, lua_code_init)
o.affect( "toto" )
o.OP( [ 5, 6, "ioo" ] )
Maybe it's possible to have a better code, if you know, please post a comment.


By the way, phrack 67 is OUT !

No comments:

Post a Comment