我需要通過它創建的順序遍歷Lua表。我發現這篇文章 - 不過,這並不好像工作:Lua有序的表迭代
function __genOrderedIndex(t)
local orderedIndex = {}
for key in pairs(t) do
table.insert(orderedIndex, key)
end
table.sort(orderedIndex)
return orderedIndex
end
function orderedNext(t, state)
-- Equivalent of the next function, but returns the keys in the alphabetic
-- order. We use a temporary ordered key table that is stored in the
-- table being iterated.
key = nil
--print("orderedNext: state = "..tostring(state))
if state == nil then
-- the first time, generate the index
t.__orderedIndex = __genOrderedIndex(t)
key = t.__orderedIndex[1]
else
-- fetch the next value
for i = 1,table.getn(t.__orderedIndex) do
if t.__orderedIndex[i] == state then
key = t.__orderedIndex[i+1]
end
end
end
if key then
return key, t[key]
end
-- no more value to return, cleanup
t.__orderedIndex = nil
return
end
function orderedPairs(t)
return orderedNext, t, nil
end
下面是使用例子:
t = {
['a'] = 'xxx',
['b'] = 'xxx',
['c'] = 'xxx',
['d'] = 'xxx',
['e'] = 'xxx',
}
for key, val in orderedPairs(t) do
print(key.." : "..val)
end
我得到一個錯誤:
attempt to call field 'getn' (a nil value)
問題是什麼?
沒有答案,但一個很好的資源:(http://devdocs.io/lua/) –