从表中选择一个随机项目 [英] Choose a random item from a table
本文介绍了从表中选择一个随机项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的目标是从Lua的一张桌子中挑选一个随机物品.
My goal is to pick out a random item from a table in Lua.
这是我到目前为止的内容,但目前无法正常工作
This is what I've got so far, but it currently does not work:
local myTable = { 'a', 'b', 'c', 'd' }
print( myTable[ math.random( 0, #myTable - 1 ) ] )
如何修复上面的代码,以使其按预期工作? (或者我可以使用哪种其他方法?)
How can I fix the above code so that it works as intended? (Or which other method could I use?)
推荐答案
Lua从1开始对表进行索引,与C,Java等不同,它从0开始对数组进行索引.这意味着,在您的表中,有效索引为:1, 2、3、4.您要寻找的是以下内容:
Lua indexes tables from 1, unlike C, Java etc. which indexes arrays from 0. That means, that in your table, the valid indexes are: 1, 2, 3, 4. What you are looking for is the following:
print( myTable[ math.random( #myTable ) ] )
当使用一个参数调用时,math.random(n)
返回一个从1到n
的随机整数,包括.
When called with one argument, math.random(n)
returns a random integer from 1 to n
including.
这篇关于从表中选择一个随机项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文