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