有更简单的方法吗?我需要获取表格中的第一个值,其索引是整数但可能不从 [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
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
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
可以在不使用当前状态的情况下调用第一个迭代器,它返回初始值,但顺序仍然不能保证。
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)
在Lua中,索引是从1开始的,没有像[0]这样的东西...它从[1]开始。
and
和or
并不能避免 falsey 的问题,例如tble[0] == false
。你需要将其改为tbl[0] == nil and tbl[1] or tbl[0]
。 - greatwolftbl = {false}
会返回nil
而不是false
,这可能不会造成问题,但并不那么明显。 - ryanpattison