Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get first table value in Lua

Tags:

lua

lua-table

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
like image 815
Yuri Astrakhan Avatar asked Jan 08 '15 22:01

Yuri Astrakhan


People also ask

How do you find the first value in a table?

We could use FIRST_VALUE() in SQL Server to find the first value from any table. FIRST_VALUE() function used in SQL server is a type of window function that results in the first value in an ordered partition of the given data set.

How do you get values in Lua?

To access the value associated with the key in a table you can use the table[key] syntax: > t = {} > t["foo"] = 123 -- assign the value 123 to the key "foo" in the table > t[3] = "bar" -- assign the value "bar" to the key 3 in the table > = t["foo"] 123 > = t[3] bar.

How do I index a table in Lua?

For Lua, that means "index the table io using the string "read" as the key". When a program has no references to a table left, Lua memory management will eventually delete the table and reuse its memory. Notice the last line: Like global variables, table fields evaluate to nil if they are not initialized.

What is a table value Lua?

Tables in Lua have the features of an OOP object like state and identity that is independent of its values. Two objects (tables) with the same value are different objects, whereas an object can have different values at different times, but it is always the same object.


1 Answers

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
like image 197
Colonel Thirty Two Avatar answered Oct 07 '22 09:10

Colonel Thirty Two