random background selection

How do I randomly select an image to be my background ? When the user dies and restarts I want to show a different background randomly chosen . Can someone help me ?

try something like this.  Assuming you have 4 background images called background1.png, background2.png, etc

local randomImage = math.random(1,4) local bg = display.newImageRect(displaygroup, "images/background"..randomImage..".png", 480, 960)

This is what I have :

 randomImage = math.random(1,4) background = display.newImageRect(displaygroup, "bg"..randomImage..".png", display.contentWidth,display.contentHeight) background.x = display.contentCenterX background.y = display.contentCenterY screenGroup:insert(background)

I am getting this error : 

game.lua:17: display.newImageRect() bad argument #1: filename or image sheet expected, but got nil

I just did this code and no background showed 

 local randomImage = math.random(1,4) local bg = display.newImageRect(displaygroup, "bg"..randomImage..".png", 480, 960)

you need to replace “displaygroup” with the name of the display group you are inserting the image in.  It’s a shorthand way of creating the image AND inserting it in 1 line of code

 I got the error . Majority of the pics are jpg  but I have two that are not . Can I put png and jpg here : “bg”…randomImage…".jpg" ?

Make them all pngs and it will work or jps - doesn’t really matter

try something like this.  Assuming you have 4 background images called background1.png, background2.png, etc

local randomImage = math.random(1,4) local bg = display.newImageRect(displaygroup, "images/background"..randomImage..".png", 480, 960)

This is what I have :

 randomImage = math.random(1,4) background = display.newImageRect(displaygroup, "bg"..randomImage..".png", display.contentWidth,display.contentHeight) background.x = display.contentCenterX background.y = display.contentCenterY screenGroup:insert(background)

I am getting this error : 

game.lua:17: display.newImageRect() bad argument #1: filename or image sheet expected, but got nil

I just did this code and no background showed 

 local randomImage = math.random(1,4) local bg = display.newImageRect(displaygroup, "bg"..randomImage..".png", 480, 960)

you need to replace “displaygroup” with the name of the display group you are inserting the image in.  It’s a shorthand way of creating the image AND inserting it in 1 line of code

 I got the error . Majority of the pics are jpg  but I have two that are not . Can I put png and jpg here : “bg”…randomImage…".jpg" ?

Make them all pngs and it will work or jps - doesn’t really matter