Reputation: 11
I've been trying my hand at lua and tried to draw a rect to the screen
-----------------------------------------------------------------------------------------
--
-- main.lua
--
-----------------------------------------------------------------------------------------
-- Variable definition:
local rect_shape
-- Initialization
rect_shape.w = 20
rect_shape.h = 40
rect_shape.x = (display.contentWidth/2)-(rect_shape.w/2)
rect_shape.y = (display.contentHeight/2)-(rect_shape.h/2)
rect_shape = display.newRect(rect_shape.x, rect_shape.y, rect_shape.w, rect_shape.h)
rect_shape:setFillColor(49,49,49)
print("value of rect_shape:", rect_shape, "value of w:", rect_shape.w, "value of h:", rect_shape.h, "value of x:", rect_shape.x, "value of y:", rect_shape.y)
when I attempt to run this script, however,
'main.lua:10: attempt to index local 'rect_enemy' (a nil value)'
is returned. So somehow it seems I need to define the components of the rect before defining the rect itself because you can't access an empty rect?
Might anyone be able to explain and help me fix this?
Upvotes: 0
Views: 53
Reputation: 2793
You redefine rect_shape
completely with...
rect_shape = display.newRect(rect_shape.x, rect_shape.y, rect_shape.w, rect_shape.h)
My feeling says it should be...
local rect_enemy = display.newRect(rect_shape.x, rect_shape.y, rect_shape.w, rect_shape.h)
rect_enemy:setFillColor(49,49,49)
Full Example
-----------------------------------------------------------------------------------------
--
-- main.lua
--
-----------------------------------------------------------------------------------------
-- Variable definition:
local rect_shape = {}
-- Initialization
rect_shape.w = 20
rect_shape.h = 40
rect_shape.x = (display.contentWidth/2)-(rect_shape.w/2)
rect_shape.y = (display.contentHeight/2)-(rect_shape.h/2)
rect_enemy = display.newRect(rect_shape.x, rect_shape.y, rect_shape.w, rect_shape.h)
rect_enemy:setFillColor(49,49,49)
print("value of rect_shape:", rect_shape, "value of w:", rect_shape.w, "value of h:", rect_shape.h, "value of x:", rect_shape.x, "value of y:", rect_shape.y)
Here rect_enemy
will be global.
You have to try if it works too if you define it local
only.
Upvotes: 0