Lua:从c导出类时的方法和属性

时间:2015-01-12 17:25:04

标签: c++ oop methods properties lua

我使用lua作为我的3d引擎的脚本语言。我有几个对象的lua“类”,现在我想使用属性而不是getter和setter。所以,而不是像这样的东西

local oldState = ui:GetChild("Panel1"):GetVisible()
ui:GetChild("Panel1"):SetVisible(not oldState)

我会

ui.Panel1.visible = not ui.Panel1.visible

问题是我的用于创建元表的C ++代码和instanced覆盖了__index方法。顺便说一下:

  1. 创建元表:

    void CLUAScript::RegisterClass(const luaL_Reg funcs[], std::string const& className)
    {
        luaL_newmetatable(m_lua_state, std::string("Classes." + className).c_str());
        luaL_newlib( m_lua_state, funcs);
        lua_setglobal(m_lua_state, className.c_str());
    }
    
  2. 实例化类(lua对象只保存指向存储在C ++代码中的实际数据的指针):

    int CLUAScript::NewInstanceClass(void* instance, std::string const& className)
    {
        if (!instance)
        {
            lua_pushnil(m_lua_state);
            return 1;
        }
    
        luaL_checktype(m_lua_state, 1, LUA_TTABLE);
    
        lua_newtable(m_lua_state);
    
        lua_pushvalue(m_lua_state,1);       
        lua_setmetatable(m_lua_state, -2);
    
        lua_pushvalue(m_lua_state,1);
        lua_setfield(m_lua_state, 1, "__index");  
    
        void **s = (void **)lua_newuserdata(m_lua_state, sizeof(void *));
    
        *s = instance;
        luaL_getmetatable(m_lua_state, std::string("Classes." + className).c_str());
        lua_setmetatable(m_lua_state, -2);
        lua_setfield(m_lua_state, -2, "__self"); 
    
        return 1; 
    }
    
  3. 问题是如何同时拥有这两种方法和属性。如果我只是将__index添加到CLUAScript::RegisterClass funcs数组,则永远不会调用它。我无法想象在CLUAScript::NewInstanceClass中删除其重新定义的方法。

    如果此代码不够,这里是使用lua的文件的链接: lua helper classfunctions for UIfunctions for Objects,和 testing lua script

1 个答案:

答案 0 :(得分:2)

  

问题是如何同时拥有方法和属性。

从广义上讲,方法只是恰好解析为函数的属性。

  

如果我只是将__index添加到RegisterClass funcs数组中,则永远不会调用它。

这是实际问题,对吧?你的其他帖子会分散注意力。

根据文件,luaL_newlib creates a new table。 luaL_newmetatable也是如此。您在RegisterClass中创建了两个表,这没有任何意义。您只需要创建元表,并且需要将__index__newindex元方法添加到此元表中。

你不能让__index简单地指向一个func表(实现类方法的快捷方式),而不是你想要在C ++类实例之间手动封送数据。属性。它必须是一个区分方法访问(值来自类范围)和属性访问(值来自实例范围)的函数。


以下是您的方法/属性访问在Lua中如何工作的示例。使用C API的细节是不同的,但方法是相同的:

-- This is the metatable you create in RegisterClass for the C++ class 'Foo'
Foo = { }

-- This is pretty close to how your __index metamethod would work in the C++ code,
-- except you're going to have to write code that resolves which field on the C++ object
-- corresponds to 'key', if any, and push that onto the stack.
function Foo.__index(instance,key)
    local method = rawget(Foo,key)
    if method then
        return method
    end
    return instance.properties[key]
end

-- This is pretty close, too, except that if you want users to be able to add properties to the Lua object
-- that coexist with the C++ object properties, you'll need to write the value to the right place.
function Foo.__newindex(instance,key,value)
    instance.properties[key] = value
end

-- this doesn't have to be a method on the metatable
function Foo:new(state)
    return setmetatable({ properties = state}, self)
end

-- example of a class method
function Foo:dump()
    print('dump:', self.x, self.y)
end

-- simulation of the userdata, an instance of your C++ class
cppClassInstance = {
    x = 10,
    y = 20,
}

obj = Foo:new(cppClassInstance)
print(obj.x) -- read `x`, which is resolved to cppClassInstance.x
obj.x = 5150 -- write to 'x', which writes to cppClassInstance.x
print(obj.x) -- witness our change
obj:dump() -- call a class method