Jump to content




[Help] Table Pick Random

lua

  • You cannot reply to this topic
5 replies to this topic

#1 MR_nesquick

  • Members
  • 106 posts
  • LocationNorway

Posted 11 May 2014 - 02:35 AM

Hello :D

i'm currently making a card game and i can't get the program not to draw the same card over and over again

i tried in my pick() function by deleting the used one but it looks like i'm misunderstanding table.remove


this is what i got so far.
Spoiler


#2 CometWolf

  • Members
  • 1,283 posts

Posted 11 May 2014 - 10:13 AM

The problem is how your getting the value. You're simply getting the index, not the actual value stored in the table itself.
local ranCard = math.random(1,#ranSort)
local ranCard = ranSort[math.random(1,#ranSort)]

table.remove will remove the given index in a table, then move the remaining indices down to fill the gap made by removing the index.
local tTable = {1,2,3}
table.remove(tTable,2)
--tTable is now {1 = 1, 2 = 3}

Edited by CometWolf, 11 May 2014 - 10:13 AM.


#3 MR_nesquick

  • Members
  • 106 posts
  • LocationNorway

Posted 11 May 2014 - 11:02 AM

Well that was easier the i though.. Thanks

#4 theoriginalbit

    Semi-Professional ComputerCrafter

  • Moderators
  • 7,332 posts
  • LocationAustralia

Posted 11 May 2014 - 11:10 AM

to expand on what CometWolf showed with table.remove
local tTable = {4,5,6}
print(table.remove(tTable,2)) --# removes the supplied index from the table and returns it, so this line will print '5'
--# tTable is now {4,6}


#5 MR_nesquick

  • Members
  • 106 posts
  • LocationNorway

Posted 11 May 2014 - 12:23 PM

Still looks like it's printing the same card twice :(
http://pastebin.com/QbZEMXJY

#6 CometWolf

  • Members
  • 1,283 posts

Posted 11 May 2014 - 01:25 PM

The problem now is that you remove the index based on the value. What Bit mentioned is very applicable to deal with that.
local ranCard = table.remove(ranSort,math.random(1,#ranSort))

Edited by CometWolf, 11 May 2014 - 01:26 PM.






2 user(s) are reading this topic

0 members, 2 guests, 0 anonymous users