9

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
Yuri Astrakhan
  • 8,808
  • 6
  • 63
  • 97

4 Answers4

9

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
Colonel Thirty Two
  • 23,953
  • 8
  • 45
  • 85
  • 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]`. – greatwolf Jan 08 '15 at 23:04
  • 3
    `tbl = {false}` will give nil instead of false. Probably not problematic but not that obvious. – ryanpattison Jan 09 '15 at 00:15
0

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.

MBlanc
  • 1,773
  • 15
  • 31
0

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)
Martin Kunc
  • 321
  • 3
  • 7
0

The index is 1-based on lua, there's no such thing like [0]...it starts at [1].