是否有任何方法獲取對象的所有非零參數/屬性 ?我發現這個:getmetadata(self.xxxx)
,我正在尋找類似的東西:getalldata(self).
如何查找lua中某個對象的所有屬性?
我目前正在參與lua的項目。不幸的是,沒有完整的參考,我不得不使用預編譯的東西。
我希望你能夠理解我想說的話。
是否有任何方法獲取對象的所有非零參數/屬性 ?我發現這個:getmetadata(self.xxxx)
,我正在尋找類似的東西:getalldata(self).
如何查找lua中某個對象的所有屬性?
我目前正在參與lua的項目。不幸的是,沒有完整的參考,我不得不使用預編譯的東西。
我希望你能夠理解我想說的話。
我要去假設當你指的是「對象」。意思是「帶有__index
的lua表格指向其他表格」。如果情況並非如此,這個答案不會對你有所幫助。
如果你的對象結構是由表格構成的(這是所有的__indexes
都是表格),那麼你可以「解析它們」來獲得所有的屬性和繼承屬性。
如果您有任何功能__index
那麼你問的是不可能的;沒有辦法獲得「函數返回非零值的值列表」。
在第一種情況下,代碼應該是這樣的:
function getAllData(t, prevData)
-- if prevData == nil, start empty, otherwise start with prevData
local data = prevData or {}
-- copy all the attributes from t
for k,v in pairs(t) do
data[k] = data[k] or v
end
-- get t's metatable, or exit if not existing
local mt = getmetatable(t)
if type(mt)~='table' then return data end
-- get the __index from mt, or exit if not table
local index = mt.__index
if type(index)~='table' then return data end
-- include the data from index into data, recursively, and return
return getAllData(index, data)
end
但要記住,如果你的任何__index
ES的是一個函數,有沒有辦法讓所有屬性;至少不是來自Lua。
我相信,對象是隻是一個表,所以你應該能夠在性能迭代任何其他表:
for i,v in ipairs(your_object) do body end
我寫我自己printObject代碼..這是
function printObj(obj, hierarchyLevel)
if (hierarchyLevel == nil) then
hierarchyLevel = 0
elseif (hierarchyLevel == 4) then
return 0
end
local whitespace = ""
for i=0,hierarchyLevel,1 do
whitespace = whitespace .. "-"
end
io.write(whitespace)
print(obj)
if (type(obj) == "table") then
for k,v in pairs(obj) do
io.write(whitespace .. "-")
if (type(v) == "table") then
printObj(v, hierarchyLevel+1)
else
print(v)
end
end
else
print(obj)
end
end
這是相反的做法,則用後前。 瀏覽表格中的所有鍵值對。如果一個索引的值是一個表,請通過該表。 這個解決方案不會像其他文章那樣得到向上的元表達式
這是用於調試目的的有用代碼。 – 2017-06-09 17:01:03
這隻會給你數字鍵「屬性」。我說的是你的意思是'雙'而不是'ipairs'。 – Jakob 2011-04-14 13:58:24
是的,這是egarcia在其更完整的解決方案中所包含的內容。感謝您指出這個錯誤。 – BMitch 2011-04-14 17:06:48