4

I have table with with multiple values and I want to print each of them.

To be like:

'value_1' 'value_2' etc..

 table = {
        {'value_1'},
        {'value_2'},
        {'value_3'},
        {'value_4'},
    }

I tried with for k, v but I failed:

for k, v in pairs(table) do
    print(v)
end
Mamun
  • 66,969
  • 9
  • 47
  • 59
whiteblXK
  • 109
  • 2
  • 3
  • 10

3 Answers3

7

The values of your table are tables themselves. So try this instead:

for k, v in pairs(table) do
    print(v[1])
end

Or create a simpler table and use your original code:

table = {
    'value_1',
    'value_2',
    'value_3',
    'value_4',
}
lhf
  • 70,581
  • 9
  • 108
  • 149
1

I'm unsure if your example was meant to be production code or not, but there are a few optimizations (although small) you could make:

-Make the table a local variable (i.e): local table = {}; -Remove the unnecessary tables (i.e): {'value1'}; >> 'value1'; -Change the k,v loop to a generic for loop (I believe that would be more efficient?).

Final code (as I would put it):

local Table = {
    "value_1";
    "value_2";
    "value_3";
    "value_4";
};

for Key = 1, #Table, 1 do
    print(Table[Key]);
end;

Feel free to ask any questions. Oh, and if you're planning on running this code many times, consider putting local print = print; above your code to define a local variable (they are faster).

levi brach
  • 11
  • 3
  • 1
    Hello, this is my finally code: https://pastebin.com/avmyfpF5, so I need to change for k,v to be more optimized? My local table is loaded only once into memory, but loop is executed many times – whiteblXK Jan 05 '18 at 10:17
0

You are working with multidimensional arrays when you have sub-tables. You can index a sub table like below.

local tab = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
}

for i, v in next, tab do
    print(i, v)
    for n, k in next, v do
        print(">", n, k)
    end
end

-- 1    table: 000001
-- > 1  1
-- > 2  2
-- > 3  3
-- 2    table: 000002
-- > 1  4
-- > 2  5
-- > 3  6
-- 3    table: 000003
-- > 1  7
-- > 2  8
-- > 3  9

To index the table above without for loops, you can use the []'s.

print(tab[1][1]) --> 1
print(tab[1][2]) --> 2
print(tab[2][1]) --> 4
print(tab[2][2]) --> 5

You are NOT restricted to number indices. You can use strings and a special way to index with them.

local tab = {
    x = 5,
    y = 10,
    [3] = 15
}

print(tab.x, tab["y"], tab[3]) --> 5   10   15   
user2262111
  • 563
  • 1
  • 6
  • 16