ssss05
ssss05

Reputation: 717

Replace a table value for a key in lua

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?

Upvotes: 2

Views: 22950

Answers (1)

jpjacobs
jpjacobs

Reputation: 9549

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.

Upvotes: 11

Related Questions