Home > Enterprise >  Change a table value with a loop in lua
Change a table value with a loop in lua

Time:12-21

I'm trying to change a value inside a table but I can't.

This is my code:

table = {{x=2}, {y=3}, {z=2}}

function printTabValue(tab, index)
    for k, v in pairs(tab[index]) do
        print(k, v)
    end
end

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

printTabValue(table,1)

I get this result:

Executing task: lua54 c:\Users\Fabio\Documents\tabletop\randomSpawnWithChat.lua <

x 2

x 2

Terminal will be reused by tasks, press any key to close it.

So, the value is the same.

How can I edit the value inside the table?

CodePudding user response:

table = {{x=2}, {y=3}, {z=2}}

is equivalent to

table = {
  [1] = {x=2},
  [2] = {y=3},
  [3] = {z=2},
}

table[1] only has one field "x" so after running your loop

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

which can be replaced by

table["x"] = 5 or table.x = 5

your table looks like this:

table = {
  [1] = {x=2},
  [2] = {y=3},
  [3] = {z=2},
  x = 5,
}

To change a single value all you need to do is this:

table[1].x = 5
  • Related