Jump to content

[TOPIC: topicViewTemplate]
[GLOBAL: userSmallPhoto]
Photo

Lua Array Shuffle Problem
Started by medimnos Apr 12 2013 12:33 AM

- - - - -
1 reply to this topic
lua array
[TOPIC CONTROLS]
This topic has been archived. This means that you cannot reply to this topic.
[/TOPIC CONTROLS]
[modOptionsDropdown]
[/modOptionsDropdown]
[reputationFilter]
[TOPIC: post.html]
#1

medimnos

[GLOBAL: userInfoPane.html]
medimnos
  • Observer

  • 8 posts
  • Corona SDK

Hi guys, i have question. 
 
This is my arraylist. 
local t = {}
t['a'] = 'a';
t['b'] = 'b';
t['c'] = 'c';
t['d'] = 'd';
 
In the loop with pairs and always return 
 
a    a
d    d
c    c
b    b
 
How can i shuffle this ? I want to change the order. Like this;
 
d      d
c      c
b      b
a      a
 
thanks in advance.


[TOPIC: post.html]
#2

thomas6

[GLOBAL: userInfoPane.html]
thomas6
  • Contributor

  • 982 posts
  • Corona SDK

local t = {"a","b","c","d"} -- original order
 
-- shuffle entries
for i = 1, #t*2 do -- repeat this for twice the amount of elements in the table, to make sure everything is shuffled well
local a = math.random(#t)
local b = math.random(#t)
t[a],t[b] = t[b],t[a]
end
 
-- print output of shuffled order
for i = 1, #t do
print(t[i])
end

 

Untested but something like this should work.




[topic_controls]
[/topic_controls]