How to get the first value of a table in Lua
Is there an easier way to do this? I need to get the very first value in a table whose indices are integers but may not start with [1]. thank!
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
source to share
If the table can start at 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 over the entire table with pairs
, since the keys can 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
source to share
pairs()
returns next()
to iterate over the table. The Lua 5.2 manual says about next
:
The order in which the indices are listed is not specified, even for numeric indices. (To traverse the table in numerical order, use the numerical value for .)
You will have to iterate over 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.
source to share