I’ve just started learning corona and lua, my 1st project is to make a little dice game and Ive just started it! heres the dice object…
--declare table + metatable
local dice = {}
local dice_mt = {__index = dice}
--CONSTRUCTOR
function dice.new(ypos, xpos)
local newdice = {xpos = xpos, ypos = ypos,dicetext = display.newText("X", 50*xpos , 50*ypos , nil, 50)}
--dicetext = display.newText(facevalue, 50*xpos , 50*ypos , nil, 50)
return setmetatable(newdice, dice_mt)
end
--rolldice function
function dice:rolldice()
self.dicetext.text = math.random(0,6)
end
return dice
the game is to have a grid of 25 dice which can be rolled (with rolldice function above)
Heres my main.lua
display.setStatusBar(display.HiddenStatusBar)
local diceclass = require ("dice")
for i = 1, 5, 1 do
local die = diceclass.new(i,i)
i = i+1
end
die:rolldice()
I’m trying to generate the grid of dice programatically (atm I am just generating 5 dice(just text) in a diagonal line. Thats fine so far but my problem is running the rolldice function. It works when there is only 1 dice but not when there is more.
I’m guessing the problem is that I have all these instances of the class with the same name.. Is there a way to give them different names programmatically as I create them in my for loop? Or is there some better way of doing this? Thanks!
localvariables are so named because they are local to the scope in which they are defined.dieis defined within theforloop. Therefore, it stops existing once you leave theforloop.If you want to create an array of
dieobjects, you need to create an array which is accessible outside of the loop, then add thedieobjects to this array.Also,
i = i+1is counter-productive, since Lua knows how to increment loops itself. Also, it may lead to undefined behavior.