Lua订购了表迭代

时间:2015-09-07 14:57:51

标签: lua lua-table

我需要按照它创建的顺序迭代Lua表。我找到了这篇文章 - http://lua-users.org/wiki/SortedIteration 但它似乎不起作用:

String str = new String(response, "UTF-8");

以下是用法示例:

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

我收到错误:

  

尝试呼叫字段' getn' (零值)

有什么问题?

1 个答案:

答案 0 :(得分:3)

自Lua 5.1以来,

<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server"> <a class="link" data-link="first" href="#">link 1</a> <a class="link" data-link="second" href="#">link 2</a> <a class="link" data-link="third" href="#">link 3</a> <div class="detailscontainer"> <div class="linkdetails" data-link="first">content 1</div> <div class="linkdetails" data-link="second">content 2</div> <div class="linkdetails" data-link="third">content 3</div> </div> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script type="text/javascript"> $('.linkdetails').hide(); $('.link').click(function() { $('.linkdetails').hide(); $('.linkdetails[data-link=' + $(this).data('link') + ']').fadeIn({ width: '200px' }, 300); }); </script> </asp:Content>已被移除,已由table.getn运算符替换。

#更改为table.getn(t.__orderedIndex)