开发者

Randoming value from table then remove it in Lua

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 ra开发者_运维问答ndom 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 with three other values to random from.

Am I confusing you? :)


table.remove(ConsoleTable, key) will indeed remove one value from the table, thus decreasing its size by 1. So the next time you call math.random(1,(#ConsoleTable)), its range will be smaller by one as well. To be honest, it looks like you are doing OK, and I'm not sure what the problem is.

Edit: How about this one-liner?

table.remove(ConsoleTable, math.random(1, #ConsoleTable))

I think this will remove one "console" at random from the table. Perhaps if you can try that and if it is not what you want, explain in detail what is wrong, we can try more things.


It's generally considered bad programming practice to remove an item from a table while you are iterating over it. Many languages get quite confused by this. If you really want to do that then you are better off creating a second mirror table, then iterating over that while removing items from your original table.

However, what I would suggest is storing the state of the consoles in the table as well and set one to inactive (state 0 perhaps) and leave the others active (state 1). Then the player can set some to active and the boss then chooses one of those and deactivates it again. You would need a few more lines of code, but it should be more flexible and easier to understand.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜