从表中随机选择一项 [英] 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屋!
查看全文