如何在Lua中获取第一个表格值

9

有更简单的方法吗?我需要获取表格中的第一个值,其索引是整数但可能不从 [1] 开始。谢谢!

local tbl = {[0]='a',[1]='b',[2]='c'}  -- arbitrary keys
local result = nil
for k,v in pairs(tbl) do -- might need to use ipairs() instead?
    result = v
    break
end
5个回答

9
如果表可能从零或一开始,但不能是其他数字:
if tbl[0] ~= nil then
    return tbl[0]
else
    return tbl[1]
end

-- or if the table will never store false
return tbl[0] or tbl[1]

否则,您只能使用 pairs 迭代整个表格,因为键可能不再存储在数组中,而是存储在无序哈希集合中。
local minKey = math.huge
for k in pairs(tbl) do
    minKey = math.min(k, minKey)
end

三元运算符中的 andor 并不能避免 falsey 的问题,例如 tble[0] == false。你需要将其改为 tbl[0] == nil and tbl[1] or tbl[0] - greatwolf
3
tbl = {false}会返回nil而不是false,这可能不会造成问题,但并不那么明显。 - ryanpattison

1
ipairs()会提供一个迭代器,从1开始以1的步长迭代,直到没有键为止,所以它会在示例代码中漏掉第0个元素。 pairs()会按照未定义的顺序迭代所有键,所以除非偶然,否则无法得到问题所要求的结果。
要获取具有任意整数键的第一个元素,您需要对键进行排序。
local function first(t)
    local keys = {}
    for k,_ in pairs(t) do
        table.insert(keys, k)
    end
    
    table.sort(keys)
    
    return t[keys[1]]
end

说到这一点,如果你需要经常这样做,你可能需要重新考虑一下数据结构。

0

pairs() 返回 next() 函数以迭代表格。Lua 5.2 手册对 next 的说明如下:

枚举索引的顺序未指定,即使是数字索引也是如此。(要按数字顺序遍历表,请使用数字 for。)

您需要迭代表格直到找到键。类似这样:

local i = 0
while tbl[i] == nil do i = i + 1 end

这段代码片段假设表至少有一个整数索引。

1
为什么不使用 ipairs 来做这件事呢? - mallwright

0

可以在不使用当前状态的情况下调用第一个迭代器,它返回初始值,但顺序仍然不能保证。

a = {[1]="I", [2]="II", [3]="III"}
-- create iterator
iter = pairs(a)

print("Calling iterator first time ")
currentKey, currentValue = iter(a)
print(currentKey, currentValue)

print("Calling iterator second time")
currentKey, currentValue = iter(a, currentKey)
print(currentKey, currentValue)

print("Calling iterator third time")
currentKey, currentValue = iter(a, currentKey)
print(currentKey, currentValue)

print("Calling iterator fourth time")
currentKey, currentValue = iter(a, currentKey)
print(currentKey, currentValue)

-1

在Lua中,索引是从1开始的,没有像[0]这样的东西...它从[1]开始。


这并不完全正确。你完全可以将[0]作为一个Lua表的条目添加进去。这是完全有效的,只是它不是默认的第一个索引。根据表的填充方式,有可能存在一个带有[0]条目但没有[1]的表。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接