有一个数组t={"a","b","c","d","e","f","g",} 求随机迭代所有值的方法.不能删除数组里的值.
不知道你说的随机迭代是什么意思.姑且按照随机打乱数组顺序吧.
function randomTable(_table, _num)
local _result = {}
local _index = 1
local _num = _num or #_table
while #_table ~= 0 do
local ran = math.random(0, #_table)
if _table[ran] ~= nil then
_result[_index] = _table[ran]
table.remove(_table,ran)
_index = _index + 1
if _index > _num then
break
end
end
end
return _result
end
function copy_table(ori_tab)
if type(ori_tab) ~= "table" then
return
end
local new_tab = {}
for k, v in pairs(ori_tab) do
local vtype = type(v)
if vtype == "table" then
new_tab[k] = copy_table[v]
else
new_tab[k] = v
end
end
return new_tab
end
function main()
t = {"a","b","c","d","e","f","g"}
f = randomTable(copy_table(t))
logDebug(table.concat(t,','))
logDebug(table.concat(f,','))
end
然后按顺序输出新数组f 就等于是随机t数组的内容且不重复了
谢谢