Replace a table value for a key in lua

13,655

That's logical.

In a loop the looping variables key and value are locals. So reassigning them, it just changes the value referenced by the local variable. After 1 run of the loop, locals run out of scope and are discarded.

To change the value in the table reference to the table itself like

 t[key]="box"

In this simple example just doing t[2]="box" would obviously also serve ;) (instead of having to loop through the whole table just to replace one value) More in depth information can be found in the manual.

Share:
13,655

Related videos on Youtube

Author by

ssss05

silence.......

Updated on June 15, 2022

Comments

  • ssss05 5 months

    I need to do replace a value for a key in lua, for example consider a table

    t = {"book", "ball", "bank"}
    

    here I need to change the value for "box" instead of "ball". how to do that ?

    previously I tried as finding the value a key and change, but it didn't work!!!

    for key, value in pairs(t) do
      if key == 2 then
        value = "box"
      end
    end
    

    but it didn't work.. if anyone knows alternative way please give me suggestions?

Related