einsteinK
|
  |
| Joined: 22 May 2011 |
| Total Posts: 1015 |
|
|
| 31 Mar 2013 02:36 PM |
A lot of players tries to get all values (and keys) from a table in a random order. Here is a little script I made for that. It's called rpairs (random-pairs ... got it? got it? no? oh -.-) and works the same. for key,value in rpairs(table) do print(key,value) end
Le script (only the local function rpairs is needed actually, rest is example): --==========-- local options = {"first","second","third",lol=game,work=workspace}
local function rpairs(tab) if type(tab) ~= "table" then error("Need a table as argument!",2) end local done = {} for k,v in pairs(tab) do done[k] = v end local function ret() local f = false for k,v in pairs(done) do f = true end while f do for k,v in pairs(done) do if math.random(1,5) == 5 then done[k] = nil return k,v end end end end return ret end
for k,v in rpairs(options) do print(k,v) end |
|
|
| Report Abuse |
|
|
|
| 31 Mar 2013 02:41 PM |
local function rpairs(tab) local indicies = {} for _, v in pairs(tab) do table.insert(indicies, _) end return function(tab) if #indicies == 0 then return end local i = math.random(1, #indicies) local ind = indicies[i] table.remove(indicies, i) return ind, tab[ind] end end
I think this works as well. |
|
|
| Report Abuse |
|
|
|
| 31 Mar 2013 02:42 PM |
| Woops. Change 'tab' in the second function to 'I' and it will work. :) |
|
|
| Report Abuse |
|
|
einsteinK
|
  |
| Joined: 22 May 2011 |
| Total Posts: 1015 |
|
|
| 31 Mar 2013 02:43 PM |
But dont' forget if they do stuff like:
for k,v in rpairs(tab) do -- if statements for stuff and other stuff tab[k+1] = nil -- for example end
then you got a little problem with your version. But for standard use yours could be better =D |
|
|
| Report Abuse |
|
|
|
| 31 Mar 2013 02:48 PM |
| Hmm, it will indeed return nil at that index. A simple if statement into my iterative function would fix that. :) |
|
|
| Report Abuse |
|
|
einsteinK
|
  |
| Joined: 22 May 2011 |
| Total Posts: 1015 |
|
|
| 31 Mar 2013 03:00 PM |
good. Because once it returns nil, the loop will stop |
|
|
| Report Abuse |
|
|
|
| 31 Mar 2013 03:02 PM |
| If the _index_ is nil, the loops stops. If the value is nil, it does not. However, if a given index has a nil value, it should not be returned in the first place. ^_^ |
|
|
| Report Abuse |
|
|
einsteinK
|
  |
| Joined: 22 May 2011 |
| Total Posts: 1015 |
|
|
| 31 Mar 2013 03:07 PM |
| the index/key of a table can NEVER be nil! NEVAH NEVAH NEVAH !!! |
|
|
| Report Abuse |
|
|
|
| 31 Mar 2013 03:10 PM |
Right. I said that wrong. XD
Nevertheless, if the random value is a nil value, and there are other indexes in the table, the loop should not stop.
^ That's what I mean to say. >_< |
|
|
| Report Abuse |
|
|