隐藏Lua metatable并仅暴露对象的属性

Sea*_*ean 4 lua metatable lua-5.2 lua-table

如何创建仅暴露其属性而不是其方法的Lua对象?例如:

local obj = {
  attr1 = 1,
  attr2 = 2,
  print = function(...)
    print("obj print: ", ...)
  end,
}
Run Code Online (Sandbox Code Playgroud)

生产:

> for k,v in pairs(obj) do print(k, v) end
attr1   1
attr2   2
print   function: 0x7ffe1240a310
Run Code Online (Sandbox Code Playgroud)

另外,是否可以在Lua中不使用OOP的冒号语法?我不需要继承,多态,只需要封装和隐私.

Sea*_*ean 10

我开始了上述问题,并追逐兔子洞后,我被实例数量有限惊讶,缺乏对各种元方法的例子(即__ipairs,__pairs,__len),以及少数的Lua 5.2资源有是如何被摄对象.

Lua可以做OOP,但IMO处理OOP的方式是对语言和社区的损害(即以支持多态,多重继承等方式).对于大多数问题,使用Lua的大部分OOP功能的原因很少.它并不一定意味着在路上也存在分叉(例如,为了支持多态性,没有任何东西表明你必须使用冒号语法 - 你可以将文献描述的技术折叠到基于闭包的OOP方法中).

我很欣赏在Lua中有很多方法可以做OOP,但是对于对象属性和对象方法(例如obj.attr1vs obj:getAttr()vs obj.method()vs obj:method())存在不同的语法令人恼火.我想要一个统一的API来进行内部和外部通信.为此,PiL 16.4关于隐私的部分是一个很好的开始,但这是一个不完整的例子,我希望用这个答案来补救.


以下示例代码:

  • 模拟类的命名空间MyObject = {}并将对象构造函数保存为MyObject.new()
  • 隐藏对象内部工作的所有细节,以便对象的用户只能看到纯表(请参阅setmetatable()__metatable)
  • 使用闭包来隐藏信息(参见Lua Pil 16.4对象基准测试)
  • 防止修改对象(见__newindex)
  • 允许拦截方法(见__index)
  • 让你获得所有函数和属性的列表(参见'key'属性__index)
  • 看起来,行为,散步,并像一个普通的Lua表会谈(见__pairs,__len,__ipairs)
  • 在需要时看起来像一个字符串(参见__tostring)
  • 与...合作 Lua 5.2

这是构造一个新的代码MyObject(这可能是一个独立的函数,它不需要存储在MyObject表中 - obj一旦创建它就没有任何联系MyObject.new(),这只是为了熟悉和超出惯例) :

MyObject = {}
MyObject.new = function(name)
   local objectName = name

   -- A table of the attributes we want exposed
   local attrs = {
      attr1 = 123,
   }

   -- A table of the object's methods (note the comma on "end,")
   local methods = {
      method1 = function()
         print("\tmethod1")
      end,

      print = function(...)
         print("MyObject.print(): ", ...)
      end,

      -- Support the less than desirable colon syntax
      printOOP = function(self, ...)
         print("MyObject:printOOP(): ", ...)
      end,
   }

   -- Another style for adding methods to the object (I prefer the former
   -- because it's easier to copy/paste function()'s around)
   function methods.addAttr(k, v)
      attrs[k] = v
      print("\taddAttr: adding a new attr: " .. k .. "=\"" .. v .. "\"")
   end

   -- The metatable used to customize the behavior of the table returned by new()
   local mt = {
      -- Look up nonexistent keys in the attrs table. Create a special case for the 'keys' index
      __index = function(t, k)
         v = rawget(attrs, k)
         if v then
            print("INFO: Successfully found a value for key \"" .. k .. "\"")
            return v
         end
         -- 'keys' is a union of the methods and attrs
         if k == 'keys' then
            local ks = {}
            for k,v in next, attrs, nil do
               ks[k] = 'attr'
            end
            for k,v in next, methods, nil do
               ks[k] = 'func'
            end
            return ks
         else
            print("WARN: Looking up nonexistant key \"" .. k .. "\"")
         end
      end,

      __ipairs = function()
         local function iter(a, i)
            i = i + 1
            local v = a[i]
            if v then
               return i, v
            end
         end
         return iter, attrs, 0
      end,

      __len = function(t)
         local count = 0
         for _ in pairs(attrs) do count = count + 1 end
         return count
      end,

      __metatable = {},

      __newindex = function(t, k, v)
         if rawget(attrs, k) then
            print("INFO: Successfully set " .. k .. "=\"" .. v .. "\"")
            rawset(attrs, k, v)
         else
            print("ERROR: Ignoring new key/value pair " .. k .. "=\"" .. v .. "\"")
         end
      end,

      __pairs = function(t, k, v) return next, attrs, nil end,

      __tostring = function(t) return objectName .. "[" .. tostring(#t) .. "]" end,
   }
   setmetatable(methods, mt)
   return methods
end
Run Code Online (Sandbox Code Playgroud)

现在用法:

-- Create the object
local obj = MyObject.new("my object's name")

print("Iterating over all indexes in obj:")
for k,v in pairs(obj) do print('', k, v) end
print()

print("obj has a visibly empty metatable because of the empty __metatable:")
for k,v in pairs(getmetatable(obj)) do print('', k, v) end
print()

print("Accessing a valid attribute")
obj.print(obj.attr1)
obj.attr1 = 72
obj.print(obj.attr1)
print()

print("Accessing and setting unknown indexes:")
print(obj.asdf)
obj.qwer = 123
print(obj.qwer)
print()

print("Use the print and printOOP methods:")
obj.print("Length: " .. #obj)
obj:printOOP("Length: " .. #obj) -- Despite being a PITA, this nasty calling convention is still supported

print("Iterate over all 'keys':")
for k,v in pairs(obj.keys) do print('', k, v) end
print()

print("Number of attributes: " .. #obj)
obj.addAttr("goosfraba", "Satoshi Nakamoto")
print("Number of attributes: " .. #obj)
print()

print("Iterate over all keys a second time:")
for k,v in pairs(obj.keys) do print('', k, v) end
print()

obj.addAttr(1, "value 1 for ipairs to iterate over")
obj.addAttr(2, "value 2 for ipairs to iterate over")
obj.addAttr(3, "value 3 for ipairs to iterate over")
obj.print("ipairs:")
for k,v in ipairs(obj) do print(k, v) end

print("Number of attributes: " .. #obj)

print("The object as a string:", obj)
Run Code Online (Sandbox Code Playgroud)

这会产生预期的 - 并且格式不佳 - 输出:

Iterating over all indexes in obj:
    attr1   123

obj has a visibly empty metatable because of the empty __metatable:

Accessing a valid attribute
INFO: Successfully found a value for key "attr1"
MyObject.print():   123
INFO: Successfully set attr1="72"
INFO: Successfully found a value for key "attr1"
MyObject.print():   72

Accessing and setting unknown indexes:
WARN: Looking up nonexistant key "asdf"
nil
ERROR: Ignoring new key/value pair qwer="123"
WARN: Looking up nonexistant key "qwer"
nil

Use the print and printOOP methods:
MyObject.print():   Length: 1
MyObject.printOOP():        Length: 1
Iterate over all 'keys':
    addAttr func
    method1 func
    print   func
    attr1   attr
    printOOP        func

Number of attributes: 1
    addAttr: adding a new attr: goosfraba="Satoshi Nakamoto"
Number of attributes: 2

Iterate over all keys a second time:
    addAttr func
    method1 func
    print   func
    printOOP        func
    goosfraba       attr
    attr1   attr

    addAttr: adding a new attr: 1="value 1 for ipairs to iterate over"
    addAttr: adding a new attr: 2="value 2 for ipairs to iterate over"
    addAttr: adding a new attr: 3="value 3 for ipairs to iterate over"
MyObject.print():   ipairs:
1   value 1 for ipairs to iterate over
2   value 2 for ipairs to iterate over
3   value 3 for ipairs to iterate over
Number of attributes: 5
The object as a string: my object's name[5]
Run Code Online (Sandbox Code Playgroud)
  • 将Lua作为外观嵌入或记录API时,使用OOP +闭包非常方便.
  • Lua OOP也可以非常,非常干净和优雅(这是主观的,但是这种风格没有任何规则 - 你总是使用a .来访问属性或方法)
  • 让一个对象的行为与表完全相同是很有用的,非常有用于脚本和询问程序的状态
  • 在沙箱中操作时非常有用

这种风格确实为每个对象消耗了更多的内存,但在大多数情况下,这不是一个问题.将metatable重新分解以供重用可以解决这个问题,尽管上面的示例代码没有.

最后的想法.一旦你驳回了文献中的大多数例子,Lua OOP实际上非常好.我不是说文学很糟糕,顺便说一句(这不可能是事实!),但是PiL和其他在线资源中的示例示例集导致您只使用冒号语法(即第一个参数为所有函数都不self是使用closureupvalue保留对(self)的引用.

希望这是一个有用的,更完整的例子.


更新(2013-10-08):上面详述的基于闭包的OOP样式有一个值得注意的缺点(我仍然认为样式值得开销,但我离题了):每个实例都必须有自己的闭包.虽然在上面的lua版本中这是显而易见的,但在处理C端的事情时,这会有些问题.

假设我们从这里开始讨论C侧的上述闭合样式.C侧的常见情况是创建一个userdatavia lua_newuserdata()对象并将metatable连接到userdatavia lua_setmetatable().在面值上,在您意识到metatable中的方法需要userdata的upvalue之前,这似乎不是问题.

using FuncArray = std::vector<const ::luaL_Reg>;
static const FuncArray funcs = {
  { "__tostring", LI_MyType__tostring },
};

int LC_MyType_newInstance(lua_State* L) {
  auto userdata = static_cast<MyType*>(lua_newuserdata(L, sizeof(MyType)));
  new(userdata) MyType();

  // Create the metatable
  lua_createtable(L, 0, funcs.size());     // |userdata|table|
  lua_pushvalue(L, -2);                    // |userdata|table|userdata|
  luaL_setfuncs(L, funcs.data(), 1);       // |userdata|table|
  lua_setmetatable(L, -2);                 // |userdata|
  return 1;
}

int LI_MyType__tostring(lua_State* L) {
  // NOTE: Blindly assume that upvalue 1 is my userdata
  const auto n = lua_upvalueindex(1);
  lua_pushvalue(L, n);                     // |userdata|
  auto myTypeInst = static_cast<MyType*>(lua_touserdata(L, -1));
  lua_pushstring(L, myTypeInst->str());    // |userdata|string|
  return 1;                                // |userdata|string|
}
Run Code Online (Sandbox Code Playgroud)

注意创建的表如何lua_createtable()与metatable名称无关,就像你已经注册了metatable一样luaL_getmetatable()?这是100%好的因为这些值在闭包之外是完全无法访问的,但它确实意味着luaL_getmetatable()不能用于查找特定userdata类型.同样,这也意味着luaL_checkudata()并且luaL_testudata()也是禁区.

底线是upvalues(userdata如上)与函数调用(例如LI_MyType__tostring)相关联,并且与userdata自身无关.截至目前,我还没有意识到可以将upvalue与值相关联的方式,以便可以跨实例共享元表.


更新(2013-10-14)我在下面包含一个小例子,它使用一个注册的metatable(luaL_newmetatable())和lua_setuservalue()/或lua_getuservalue()一个userdata's"属性和方法".还添加了随机评论,这些评论一直是我过去常常遇到的错误/热情的根源.还提出了一个C++ 11技巧来帮助__index.

namespace {

using FuncArray = std::vector<const ::luaL_Reg>;
static const std::string MYTYPE_INSTANCE_METAMETHODS{"goozfraba"}; // I use a UUID here
static const FuncArray MyType_Instnace_Metamethods = {
  { "__tostring", MyType_InstanceMethod__tostring },
  { "__index",    MyType_InstanceMethod__index },
  { nullptr,      nullptr }, // reserve space for __metatable
  { nullptr, nullptr } // sentinel
};

static const FuncArray MyType_Instnace_methods = {
  { "fooAttr", MyType_InstanceMethod_fooAttr },
  { "barMethod", MyType_InstanceMethod_barMethod },
  { nullptr, nullptr } // sentinel
};

// Must be kept alpha sorted
static const std::vector<const std::string> MyType_Instance___attrWhitelist = {
  "fooAttr",
};

static int MyType_ClassMethod_newInstance(lua_State* L) {
  // You can also use an empty allocation as a placeholder userdata object
  // (e.g. lua_newuserdata(L, 0);)
  auto userdata = static_cast<MyType*>(lua_newuserdata(L, sizeof(MyType)));
  new(userdata) MyType(); // Placement new() FTW

  // Use luaL_newmetatable() since all metamethods receive userdata as 1st arg
  if (luaL_newmetatable(L, MYTYPE_INSTANCE_METAMETHODS.c_str())) { // |userdata|metatable|
    luaL_setfuncs(L, MyType_Instnace_Metamethods.data(), 0); // |userdata|metatable|

    // Prevent examining the object: getmetatable(MyType.new()) == empty table
    lua_pushliteral(L, "__metatable");     // |userdata|metatable|literal|
    lua_createtable(L, 0, 0);              // |userdata|metatable|literal|table|
    lua_rawset(L, -3);                     // |userdata|metatable|
  }

  lua_setmetatable(L, -2);                 // |userdata|

  // Create the attribute/method table and populate with one upvalue, the userdata
  lua_createtable(L, 0, funcs.size());     // |userdata|table|
  lua_pushvalue(L, -2);                    // |userdata|table|userdata|
  luaL_setfuncs(L, funcs.data(), 1);       // |userdata|table|

  // Set an attribute that can only be accessed via object's fooAttr, stored in key "fooAttribute"
  lua_pushliteral(L, "foo's value is hidden in the attribute table"); // |userdata|table|literal|
  lua_setfield(L, -2, "fooAttribute");     // |userdata|table|

  // Make the attribute table the uservalue for the userdata
  lua_setuserdata(L, -2);                  // |userdata|
  return 1;
}

static int MyType_InstanceMethod__tostring(lua_State* L) {
  // Since we're using closures, we can assume userdata is the first value on the stack.
  // You can't make this assumption when using metatables, only closures.
  luaL_checkudata(L, 1, MYTYPE_INSTANCE_METAMETHODS.c_str()); // Test anyway
  auto myTypeInst = static_cast<MyType*>(lua_touserdata(L, 1));
  lua_pushstring(L, myTypeInst->str());    // |userdata|string|
  return 1;                                // |userdata|string|
}

static int MyType_InstanceMethod__index(lua_State* L) {
  lua_getuservalue(L, -2);        // |userdata|key|attrTable|
  lua_pushvalue(L, -2);           // |userdata|key|attrTable|key|
  lua_rawget(L, -2);              // |userdata|key|attrTable|value|
  if (lua_isnil(L, -1)) {         // |userdata|key|attrTable|value?|
    return 1;                     // |userdata|key|attrTable|nil|
  }

  // Call cfunctions when whitelisted, otherwise the caller has to call the
  // function.
  if (lua_type(L, -1) == LUA_TFUNCTION) {
    std::size_t keyLen = 0;
    const char* keyCp = ::lua_tolstring(L, -3, &keyLen);
    std::string key(keyCp, keyLen);

    if (std::binary_search(MyType_Instance___attrWhitelist.cbegin(),
                           MyType_Instance___attrWhitelist.cend(), key))
    {
      lua_call(L, 0, 1);
    }
  }

  return 1;
}

static int MyType_InstanceMethod_fooAttr(lua_State* L) {
  // Push the uservalue on to the stack from fooAttr's closure (upvalue 1)
  lua_pushvalue(L, lua_upvalueindex(1)); // |userdata|
  lua_getuservalue(L, -1);               // |userdata|attrTable|

  // I haven't benchmarked whether lua_pushliteral() + lua_rawget()
  // is faster than lua_getfield() - (two lua interpreter locks vs one lock + test for
  // metamethods).
  lua_pushliteral(L, "fooAttribute");    // |userdata|attrTable|literal|
  lua_rawget(L, -2);                     // |userdata|attrTable|value|

  return 1;
}

static int MyType_InstanceMethod_barMethod(lua_State* L) {
  // Push the uservalue on to the stack from barMethod's closure (upvalue 1)
  lua_pushvalue(L, lua_upvalueindex(1)); // |userdata|
  lua_getuservalue(L, -1);               // |userdata|attrTable|

  // Push a string to finish the example, not using userdata or attrTable this time
  lua_pushliteral(L, "bar() was called!"); // |userdata|attrTable|literal|

  return 1;
}

} // unnamed-namespace
Run Code Online (Sandbox Code Playgroud)

lua脚本方面看起来像:

t = MyType.new()
print(typue(t))    --> "userdata"
print(t.foo)       --> "foo's value is hidden in the attribute table"
print(t.bar)       --> "function: 0x7fb560c07df0"
print(t.bar())     --> "bar() was called!"
Run Code Online (Sandbox Code Playgroud)