Add members dynamically to a class using Lua + SWIG

后端 未结 1 1899
庸人自扰
庸人自扰 2021-01-16 07:21

This Lua code, creates a table and dynamically adds a new member. Running this I can get \"hello\" on the screen as expected:

foo = {}
foo.x = \         


        
相关标签:
1条回答
  • 2021-01-16 07:49

    SWIG doesn't use tables for its objects; it uses userdata. After all, those objects are C++ objects, and need to store C++ data that Lua code shouldn't be able to touch.

    And I wouldn't bother looking for "another Lua binding library"; pretty much all of them use userdata, which Lua code explicitly cannot modify (in order to provide the ability to do exactly this).

    However, that doesn't mean you can't cheat.

    You can always wrap the object you get from C++ code into your own Lua table, which would have a metatable that forwards unknown calls to the C++ object. The code to do so would look something like this:

    local function WrapObject(cppObject)
    
        local proxy = {}
    
        local wrapper_metatable = {}
    
    function wrapper_metatable.__index(self, key)
        local ret = rawget(self, key)
        if(not ret) then
            ret = cppObject[key]
            if(type(ret) == "function") then
                return function(self, ...)
                    return ret(cppObject, ...)
                end
            else
                return ret
            end
        else
            return ret
        end
    
    end
    
    
        setmetatable(proxy, wrapper_metatable)
        return proxy
    end
    

    The returned proxy object is a Lua table that can have keys and values set on it. When you get a value, such as to call a function, it will see if that value was set in the table. If not, it attempts to fetch it from the C++ object that you wrapped, which will go through its metatable.

    You'll need to expand this metatable if your C++ class uses other metafunctions like __add, __sub, __tostring and so forth.

    0 讨论(0)
提交回复
热议问题