How do I get first table value in Lua

25,645

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
Share:
25,645
Yuri Astrakhan
Author by

Yuri Astrakhan

Maps/OpenStreetMap, Wikipedia, Wikidata, ElasticSearch, Kibana, Vega/DataViz, large datasets... Author of Wikipedia API/maps/graphs. DevOps and Maps Principal Engineer at Elastic.

Updated on January 09, 2020

Comments

  • Yuri Astrakhan
    Yuri Astrakhan over 4 years

    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
    
  • greatwolf
    greatwolf over 9 years
    The ternary and or above doesn't avoid the falsey caveat, eg. tble[0] == false. You'll have to switch it around tbl[0] == nil and tbl[1] or tbl[0].
  • ryanpattison
    ryanpattison over 9 years
    tbl = {false} will give nil instead of false. Probably not problematic but not that obvious.
  • mallwright
    mallwright about 2 years
    Why not use ipairs for this?