'How to get x first objects from table - lua

I'm pretty new in lua and I have a problem that I've been trying to solve for several hours now. So simply I have one table with 4 other tables (sry idk how it's named).

local myTable = {
 player1 = {id = 1, points = 100},
 player2 = {id = 3, points = 200},
 player3 = {id = 4, points = 150},
 player4 = {id = 7, points = 150}}

Id and points are random numbers. All I want to do is get only 2 first tables from that table and use their values.

player1 = {id = 1, points = 100}
player2 = {id = 3, points = 200}

I would really appreciate your help, it's very tiring.



Solution 1:[1]

All I want to do is get only 2 first tables from that table and use their values.

To get the inner tables just index myTable with the keys you've stored to inner tables at.

local table1 = myTable.player1
local table2 = myTable.player2

print("Player 1 has " .. table1.points .. " points")

How to get x first objects from table - lua

To answer this you would need to have a table with an order. Lua doesn't know the order of your table unless you have numerical keys.

If your table was like

local players = {
 {id = 1, points = 100},
 {id = 3, points = 200},
 {id = 4, points = 150},
 {id = 7, points = 150}}

You would simply pick players[1] and so forth to get the first x elements.

In your case you could do something like

myTable["player"..i] for i from 1 to x assuming that the keys represent the table order.

Solution 2:[2]

First you need is sort your table:

local myTable = {
    {id = 1, points = 100},
    {id = 3, points = 200},
    {id = 4, points = 150},
    {id = 7, points = 150}
}

You don't need to index those values as 'player1', 'player2', etc. So if you want the index(es) to appear as player1, etc. return the index and concatenated as player, like:

for key, value in pairs(myTable) do
    print('player' .. key)
end

The past code will print all table indexes with prefix 'player'. But to get only the first two values; what we can do? Simple! Make a function:

local myTable = {
    {id = 1, points = 100},
    {id = 3, points = 200},
    {id = 4, points = 150},
    {id = 7, points = 150}
}

local function collect(table, howMuch)
    local response, index = {}, 1
    for key, value in pairs(table) do
        response[key] = howMuch and index <= howMuch and value or nil
        index = index + 1
    end
    return response
end

local response = collect(myTable, 2)
print(response[1].id, response[2].id, response[3]) -- 1, 3, nil

What this function do? Collect values from the first argument named table, and in base the second argument named howMuch (as a max of the response) return those values.

Or for friends: iters table myTable and only returning a table containing 2 fields.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2