Reputation: 10035
Is there an easier way to do this? I need to get the very first value in a table, whose indexes are integers but might not start at [1]. Thx!
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
Upvotes: 13
Views: 43794
Reputation: 19
ipairs() will provide an iterator that starts at 1 and iterates in steps of 1 until there is no key there so it will miss out the 0th element in the example code.
pairs() will iterate over all the keys but in an undefined order so will not give what the question asked for either except by accident.
To get the first element with arbitrary integer keys, you would have to sort the keys.
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
Having said that, if you are needing to do this a lot you might want to rethink the data structure a bit.
Upvotes: 1
Reputation: 471
It is possible to call the first iterator without the current state, which returns initial value, but the order is still not guarantueed.
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)
Upvotes: 0
Reputation: 26609
If the table may start at either zero or one, but nothing else:
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]
Otherwise, you have no choice but to iterate through the whole table with pairs
, as the keys may no longer be stored in an array but rather in an unordered hash set:
local minKey = math.huge
for k in pairs(tbl) do
minKey = math.min(k, minKey)
end
Upvotes: 11
Reputation: 1783
pairs()
returns the next()
function to iterate the table. The Lua 5.2 manual says this about next
:
The order in which the indices are enumerated is not specified, even for numeric indices. (To traverse a table in numeric order, use a numerical for.)
You'll have to iterate the table until you find the key. Something like:
local i = 0
while tbl[i] == nil do i = i + 1 end
This code snippet makes the assumption that the table has at least 1 integer index.
Upvotes: 0