开发者

How can I compress a table after having removed a value from it?

开发者 https://www.devze.com 2023-01-28 16:58 出处:网络
I have a table which contains 4 values. For example: 2 4 1 3 I use a function to step through the table looking for, lets say the number 1 by using pairs and to get the position of it in the table

I have a table which contains 4 values.

For example:

2
4
1
3

I use a function to step through the table looking for, lets say the number 1 by using pairs and to get the position of it in the table.

I then use table.remove to remove 1 from that position. What I would like to do now is to compress the table so that it is 3 values long 2 4 3

I'm fairly new to LUA so be gentle with me. :)

What I have is pretty much this:

CloseRandomConsole = math.random(1,(#ConsoleTable)) 

If CloseRandomConsole == 1 then 
 for key, value in pairs(ConsoleTable) do 
 if value == "1" then 
  table.remove(ConsoleTable, key) 
 break 
 end 
end 

I see where I'm going wrong but I hae no idea how to solve it.

math.random(1,(#ConsoleTable))

I only want to be able to random between one of the values in the table. And when I have randomed that vlue I want it removed so that I will be left w开发者_Python百科ith three other values to random from.

Am I confusing you? :)


What do you mean?

s = {2,4,1,3} -- the table
for k,v in pairs(s) do 
  if v==1 then 
     table.remove(s,k)
  end
end

print(#s) -- is now 3
for k,v in pairs(s) do print(v) end -- just the 3 values ...

@Vitae: When you're asking about anything, you should describe what you want to do, not how you want to do it -- especially when you have no idea what you're doing ...

Maybe you want to remove a random value from the table? Then fetch the value at a random index ...

function poprandom( t )
  local idx = math.random(1,#t)
  local ret = t[idx]
  table.remove(t, idx)
  return ret
end
0

精彩评论

暂无评论...
验证码 换一张
取 消