Search code examples
lualua-table

How do I get first table value in Lua


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

Solution

  • 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