set/getmetatable與debug.set/getmetatable

--set/getmetatable

{"setmetatable", luaB_setmetatable},
{"getmetatable", luaB_getmetatable},

static int luaB_setmetatable (lua_State *L) {
  int t = lua_type(L, 2);
  luaL_checktype(L, 1, LUA_TTABLE);
  luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,
                    "nil or table expected");
  if (luaL_getmetafield(L, 1, "__metatable"))
    luaL_error(L, "cannot change a protected metatable");
  lua_settop(L, 2);
  lua_setmetatable(L, 1);
  return 1;
}

static int luaB_getmetatable (lua_State *L) {
  luaL_checkany(L, 1);
  if (!lua_getmetatable(L, 1)) {
    lua_pushnil(L);
    return 1;  /* no metatable */
  }
  luaL_getmetafield(L, 1, "__metatable");
  return 1;  /* returns either __metatable field (if present) or metatable */
}
--debug.set/getmetatable

{"setmetatable", db_setmetatable},
{"getmetatable", db_getmetatable},

static int db_setmetatable (lua_State *L) {
  int t = lua_type(L, 2);
  luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,
                    "nil or table expected");
  lua_settop(L, 2);
  lua_pushboolean(L, lua_setmetatable(L, 1));
  return 1;
}

static int db_getmetatable (lua_State *L) {
  luaL_checkany(L, 1);
  if (!lua_getmetatable(L, 1)) {
    lua_pushnil(L);  /* no metatable */
  }
  return 1;
}

可以看到,兩者不同的地方在于,setmetatable 有檢測(cè) __metatable 鍵值,如果存在,setmetatable 會(huì)失敗。而 getmetatable 會(huì)優(yōu)先返回 __metatable 鍵值的內(nèi)容,不存在再返回 metatable。舉例說(shuō)明:

local a = {}
setmetatable(a, {__metatable = "lock"})
print(type(getmetatable(a)), getmetatable(a))
print(type(debug.getmetatable(a)), debug.getmetatable(a))
debug.setmetatable(a, {__metatable = "lock2"})
setmetatable(a, {__metatable = "lock2"})
image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Lua 5.1 參考手冊(cè) by Roberto Ierusalimschy, Luiz Henrique de F...
    蘇黎九歌閱讀 14,257評(píng)論 0 38
  • 在 Lua table 中我們可以訪問(wèn)對(duì)應(yīng)的key來(lái)得到value值,但是卻無(wú)法對(duì)兩個(gè) table 進(jìn)行操作。 因...
    NeoSam閱讀 546評(píng)論 0 1
  • 1.模塊與包 基礎(chǔ)知識(shí) 模塊類似于一個(gè)封裝庫(kù),從 Lua 5.1 開始,Lua 加入了標(biāo)準(zhǔn)的模塊管理機(jī)制,可以把一...
    ClownWang閱讀 478評(píng)論 0 0
  • 前言 元表對(duì)應(yīng)的英文是metatable,元方法是metamethod。我們都知道,在C++中,兩個(gè)類是無(wú)法直接相...
    BobWong閱讀 1,125評(píng)論 0 9
  • 元表 在 Lua 5.1 語(yǔ)言中,元表 (metatable) 的表現(xiàn)行為類似于 C++ 語(yǔ)言中的操作符重載,例如...
    tcgx閱讀 900評(píng)論 0 0

友情鏈接更多精彩內(nèi)容