2015-03-02 54 views
1

我试图从表中随机获取一个项目。我在网上搜索,但我找到的所有代码都不起作用。我的表看起来像这样:Love2d:表中的随机元素

section = {a, b} 
love.graphics.newImage("/Images/a.png") 
love.graphics.newImage("/Images/b.png")  
love.graphics.draw(section[imath.random(#section)], x, y) 

我需要从这个表中的一个随机项目。

+1

的可能重复[Lua中选择从表中随机项(http://stackoverflow.com/questions/2988246/lua-从表中选择随机项) – Adam 2015-03-02 17:42:34

+0

这两个答案都来自[Lua从表中选择随机项](http://stackoverflow.com/questions/2988246/lua-choose-random-item-from-table)不要与信件一起工作。 – 2015-03-02 17:55:01

回答

2

试试这个:

item = section[math.random(#section)] 

在您的例子:

section = { 
    love.graphics.newImage("/Images/a.png"), 
    love.graphics.newImage("/Images/b.png"), 
}  
love.graphics.draw(section[math.random(#section)], x, y) 
+0

用字母返回零,但与数字一起使用。 – 2015-03-02 17:45:25

+1

@ math.random,如果你想要字母,使用'section = {“a”,“b”,“c”,“f”,“z”}'。 – lhf 2015-03-02 18:13:53

+0

我需要这个来加载一个随机的.png。这是代码:'love.graphics.newImage(“/ Images/a.png”).... love.graphics.newImage(“/ Images/b.png”)love.graphics.draw(section [imath。随机(#部分)],x,y)' – 2015-03-02 18:25:22