Find and replace on table

Posted by Shashank on Mon 18 Oct 2010 06:59 PM — 5 posts, 21,093 views.

#0
Can I use the replace function on all the elements of the table

Suppose I have the table
agh
0p9
pl0
0lw

Three different columns

I want to replace the strings "0" to NULL or a default value

I am trying to use the replace function in the foreach function

function rep(input)
t=string.replace(input,"0",nil)
end;

output=table.foreachi(input,rep)

I am finding difficulty using this ..

Thanks
Amended on Mon 18 Oct 2010 07:07 PM by Shashank
#1
try going through the table, value by value, and if the value = nil or "" then "null" or whatever.

I'm trying to figure out how you've gotten a 3-column table. I thought tables in Lua were key/value pairs.
#2
Thanks I would do for each column
Australia Forum Administrator #3
It depends a bit on whether the table is numerically keyed, and whether you want gaps afterwards. First example:



function fixtable (t)
  for k, v in pairs (t) do
    if v == 0 then
      t [k] = nil
    end -- if
  end -- for
end -- function fixtable 


t = { 22, 33, 44, 0, 62, 18, 0, 6 }

print ("before", #t)

fixtable (t)

print ("after", #t)

require "tprint"

tprint (t)

Output
before 8
after 8
1=22
2=33
3=44
5=62
6=18
8=6


Note that the table length is still reported as 8, even though there are actually 6 items left.


However if you use table.remove you can remove things from a numerically keyed table and shuffle the others down (there would be a speed penalty for very large tables).



function fixtablev2 (t)
  for i = #t, 1, -1 do
    if t [i] == 0 then
      table.remove (t, i)
    end -- if
  end -- for
end -- function fixtablev2 

t = { 22, 33, 44, 0, 62, 18, 0, 6 }

print ("before", #t)

fixtablev2 (t)

print ("after", #t)

require "tprint"

tprint (t)

Output
before 8
after 6
1=22
2=33
3=44
4=62
5=18
6=6


In this case the length of the table is now reported as 6. I went backwards through the table because I was worried about deleting items upwards (eg. if you delete item 2, then the for loop will probably skip item 3 which will now become item 2).
Amended on Mon 18 Oct 2010 08:55 PM by Nick Gammon
Australia Forum Administrator #4
Shashank said:

I want to replace the strings "0" to NULL or a default value


I should point out that in Lua, tables can't contain a key item with a value of nil. So putting nil into the value effectively deletes the item. Thus putting in a default value, and putting in nil, do two completely different things.