1

I am experimenting with using JNLua's javavm module to connect with and extend a Java library (JAR). So far I am super impressed with how easy it is to pass Java objects back and forth between Lua and Java- seemlessness.

Now I am interested to extend these Java objects in LUA. In my naive approach I've wrapped the Java object in a Lua class with the intent of extending that objects API i.e. adding methods to it. But I don't want to have to recreate, within the wrapper, all of the Java objects methods. It seems like I should be able to inherit from the Java object so that when a method is missing from my wrapper Lua will look for it in the Java object which is a member of the wrapped class. I've tried adapting the examples shown in Inheritance but this is a slightly trickier thing to set up, given that I'm dealing with a Java object. Thoughts?

1 Answers1

0

I found my answer in the below SO question

Add members dynamically to a class using Lua + SWIG

  1. I needed to realize I was dealing with a UserData object, not a table- no way to add members
  2. I needed some metatable kung-fu

The below code has the effect of allowing me to extend (add methods) a Java object.

            function Model:new (model)

               o = {}

               WrapObject(Model, o, model)

               self.__index = self
               self.model = model or nil
               return o
            end


            function WrapObject(class, object, userData)

                local wrapper_metatable = {}

            function wrapper_metatable.__index(self, key)
                local ret = rawget(class, key)
                if(not ret) then
                    ret = userData[key]
                    if(type(ret) == "function") then
                        return function(self, ...)
                            return ret(userData, ...)
                        end
                    else
                        return ret
                    end
                else
                    return ret
                end
            end

                setmetatable(object, wrapper_metatable)
                return object
            end

            function Model:Test ()

              name = self:GetFullName()
              fileName = self:GetFileName()

              ret = name .. fileName
              print("It's a test!!")

              return ret

            end
Community
  • 1
  • 1