Runtime error in OOP class (Corona) - coronasdk

New to Corona (coming from Actionscript) and trying to work through some OOP tutorials to create reusable modules for my app. Currently working on a number picker, which seems to be working, but also throwing an error when I press the buttons. Here's the code for the 'numberPicker.lua':
local numberPicker = {}
local numberPicker_mt = { __index = numberPicker } -- metatable
widget = require "widget"
-------------------------------------------------
-- PUBLIC FUNCTIONS
-------------------------------------------------
function numberPicker.new() -- constructor
local newNP = display.newGroup()
local value = 0
local function dec()
print("dec")
if value > 0 then
value = value - 1
valueText.text = value
end
end
local function inc()
print("inc")
if value < 100 then
value = value + 1
valueText.text = value
end
end
decrement = widget.newButton{
default="gfx/dec_normal.png",
over="gfx/dec_press.png",
width=58, height=58,
onRelease = dec
}
valueText = display.newText(value, 70, 10, native.systemFont, 40)
valueText:setTextColor(0, 0, 0)
increment = widget.newButton{
default="gfx/inc_normal.png",
over="gfx/inc_press.png",
width=58, height=58,
onRelease = inc
}
increment.x = 140
newNP:insert(decrement.view)
newNP:insert(valueText)
newNP:insert(increment.view)
return setmetatable( newNP, numberPicker_mt )
end
return numberPicker
usage:
local numberPicker = require( "numberPicker" )
local lengthPicker = numberPicker.new()
scrollView:insert(lengthPicker)
When I press either button, I get the following error printing out twice:
Runtime error
attempt to call a nil value
stack traceback:
[C]: ?
Any clues anyone?
Thanks,
Emma.

"scrollView" variable was not initialized.

Related

Lua/Corona Attempt to Index a Boolean Value

It looks like I am having problems with transitioning from my level select page to my first level. I think it might be that I am missing something in my level 1, but I don't know exactly.
levelSelect.lua
module(..., package.seeall)
local director = require ("director")
local physics = require("physics")
physics.start()
local widget = require( "widget" )
-- Function to handle button events
local function handleButtonEventLevel1( event )
local phase = event.phase
if "ended" == phase then
director:changeScene("lvl1")
end
end
--local function goLevel1()
--director:changeScene("lvl1")
--return true
--end
--widget.newButton:addEventListener("tap", goLevel1)
local function handleButtonEventToPage( event )
local phase = event.phase
if "ended" == phase then
director:changeScene("page")
end
end
-- Main function - MUST return a display.newGroup()
function new()
local localGroup = display.newGroup()
local background = display.newImage("bigtestsky.png")
background.x=150
background.y=250
local myButton = widget.newButton
{
left = 25,
top = 25,
width = 100,
height = 50,
defaultFile = "default.png",
overFile = "over.png",
label = "1",
font = "LS",
fontSize = 20,
labelColor = { default = {0,0,50}, over = {0,0,255} },
onEvent = handleButtonEventLevel1,
}
local myButton = widget.newButton
{
left = 25,
top = 415,
width = 100,
height = 50,
defaultFile = "default.png",
overFile = "over.png",
label = "BACK",
font = "LS",
fontSize = 20,
labelColor = { default = {0,0,50}, over = {0,0,255} },
onEvent = handleButtonEventToPage,
}
return localGroup
end
lvl1.lua
local physics = require("physics")
physics.start()
local widget = require( "widget" )
(This is what I mean about missing something in the first level. Could someone please help?)
stack traceback:
[C]: ?
.../myName/Desktop/Bubbles! App/director.lua:116: in function 'loadScene'
.../myName/Desktop/Bubbles! App/director.lua:394: in function 'changeScene'
...myName/Desktop/Bubbles! App/levelSelect.lua:14: in function '_onEvent'
?: in function '?'
?: in function <?:405>
?: in function <?:218>
These are due to some issues with your class: lvl1.lua.
If such error occurs, open director.lua analyse the error return line. This will help you to find what the real problem is.
Here, you must write more lines in your lvl1.lua as below:
module(...,package.seeall) -- If this line is not written, then the package will not be loaded.
function new() -- Module 'lvl1' must have a new() function
local localGroup = display.newGroup() -- The scene should create a display group
local physics = require("physics")
physics.start()
local widget = require( "widget" )
print("Inside lvl1...")
return localGroup; -- And the scene should return the previously created display group.
end
Keep Coding.............. :)

Corona SDK: Displaying Word from Table

OK my first question was too vague so I'm going to start simple here. I am trying to get a random word from a table in another lua file (content.lua). I have gotten the code to run without errors but cannot get a word to display on the screen or via print in the command console. What am I missing?
game.lua
--lua for game
--Loading the local variables
--creates the storyboard variable and calls the storyboard api
local storyboard = require ("storyboard")
--calls the mydata.lua module
local myData = require( "mydata" )
--calls the sfx.lua where sounds are stored
local sfx = require( "sfx" )
--calls the operations.lua
local operations = require("operations")
local content = require("content")
local playOrder
local wordGraphic
local currQuestion = 1
local homeButton
--tells storyboard to create a new scene
local scene = storyboard.newScene()
function scene:createScene(event)
local gameScreen = self.view
--creates a transparent background image centered on the display
local gameBackground = display.newImage("images/graphics/jungle1.jpg")
gameBackground.x = display.contentWidth/2
gameBackground.y = display.contentHeight/2
gameScreen:insert(gameBackground)
homeButton = display.newImage("images/buttons/home.png")
homeButton.alpha = .8
homeButton.y = 70
gameScreen:insert(homeButton)
playOrder = operations.getRandomOrder(#content)
end
local function onHomeTouch(event)
if event.phase == "began" then
storyboard.gotoScene("start")
end
end
function scene:enterScene(event)
homeButton:addEventListener("touch", onHomeTouch)
audio.play(sfx.Bkgd)
--uses the operations.lua to get words in a random order from the content.lua
--shows a random word from the content.lua table
function showWord()
local word = content[playOrder[currQuestion]].word
print(word)
wordGraphic = self.view
wordGraphic:insert(word)
wordGraphic.x = display.contentWidth/2
wordGraphic.y = display.contentHeight/2
end
end
--next question function which clears the screen and loads a new random word
function scene:exitScene(event)
homeButton:removeEventListener("touch", onHomeTouch)
end
function scene:destroyScene(event)
end
--the actual event listeners that make the functions work
scene:addEventListener("createScene", scene)
scene:addEventListener("enterScene", scene)
scene:addEventListener("exitScene", scene)
scene:addEventListener("destroyScene", scene)
return scene
Here is the operations.lua that gets the random order function
--operations.lua
module(..., package.seeall)
--function to get a random piece of data
function getRandomOrder(amount)
local order ={}
local i
local temp
local temp1
for n = 1,amount do
order[n] = n
end
for i=0,9 do
for temp = 1,amount do
n = math.random(1, amount)
temp1 = order[temp]
order[temp] = order[n]
order[n] = temp1
end
end
return order
end
This is where the words I am attempting to display are stored. I did not include all of them.
--content.lua
return {
{
id = "after",
word = "after"
},
{
id = "again",
word = "again"
},
{
id = "an",
word = "an"
},
{
id = "any",
word = "any"
},
{
id = "ask",
word = "ask"
},
{
id = "as",
word = "as"
},
{
id = "by",
word = "by"
}
}
You're not calling showWord in any of the code that you've shown so far. This is probably why it isn't even printing to the console. The function is just contained within scene:enterScene and exits to the outer scope, defining itself as a global variable when enterScene is called.

attempt to call method 'insert' (a nil value)

How come I get a attempt to call method 'insert' (a nil value) error on the line containing insert?
Changing it to instance.sprites = bg does make it work, but I want to return all sprites in a separate table (sprites).
local writingTool = {}
local _W, _H = display.contentWidth, display.contentHeight
function writingTool:new()
local instance = {}
instance.index = writingTool
setmetatable(instance, self)
instance.sprites = {}
local bg = display.newImage("images/backgrounds/wooden_bg.png")
bg.x = _W/2
bg.y = _H/2
instance.sprites:insert(bg)
return instance
end
return writingTool
Edit: Trying instance.sprites.bg = bg does not work either. Give this error:
bad argument #-2 to 'insert' (Proxy expected, got nil)
instance.index = writingTool
Should be
instance.__index = writingTool
Though I would remove the above line and implement it in the one below like so:
setmetatable(instance,{__index=writingTool})
Also, t:insert() or t.insert() aren't defined by default, to insert elements into a table you use the table.insert function as defined below:
table.insert (table, [pos,] value)
so you should have table.insert(instance.sprites,bg). So with these modifications your function should look like:
function writingTool:new()
local instance = { sprites = {} }
setmetatable(instance, {__index = wirtingTool})
local bg = display.newImage("images/backgrounds/wooden_bg.png")
bg.x = _W/2
bg.y = _H/2
table.insert(instance.sprites,bg)
return instance
end

Is This A lua Variable Scope Issue (and how can it be solved)?

A very strange error, showing an object is nil.
the code in subject is
while pbs:HasNext() do
local char = self.DecodeCharacter(pbs)
...
One would think, that if pbs:HasNext() is true, it means that, pbs is not nil, whatsoever.
However, the print(pbs) - the first line of HTMLEntityCodec:DecodeCharacter prints nil
function HTMLEntityCodec:DecodeCharacter(pbs)
print(pbs)
...
The entire file dumped below, it was stripped from 1800+ lines to 110 so it can be clear for SO users to get he context. But that stripping took away all logic from the code, so do not get confused by that.
#!/usr/bin/env lua
function Inherits( baseClass )
local new_class = {}
local class_mt = { __index = new_class }
function new_class:create()
local newinst = {}
setmetatable( newinst, class_mt )
return newinst
end
if baseClass then
setmetatable( new_class, { __index = baseClass } )
end
return new_class
end
-------------------------------------------
-- PushbackString
-------------------------------------------
PushbackString = Inherits({})
function PushbackString:Init(input)
self.input = input
self.pushback = nil
self.temp = nil
self.index = 0
self.mark = 0
end
-- Mark the current index, so the client can reset() to it if need be.
function PushbackString:HasNext()
return true
end
function PushbackString:Mark ()
self.temp = self.pushback
self.mark = self.index
end
BaseCodec = Inherits({})
function BaseCodec:Decode(input)
local buff = ''
local pbs = PushbackString:create()
pbs:Init(input)
while pbs:HasNext() do
local char = self.DecodeCharacter(pbs)
if char ~= nil then
buff = buff .. char
else
buff = buff .. pbs:Next()
end
end
return buff
end
HTMLEntityCodec = Inherits(BaseCodec)
-- HTMLEntityCodec.classname = ('HTMLEntityCodec')
function HTMLEntityCodec:DecodeCharacter(pbs)
print(pbs)
pbs:Mark()
end
DefaultEncoder = Inherits({})
function DefaultEncoder:Init(codecs)
self.html_codec = HTMLEntityCodec:create()
end
function DefaultEncoder:TestInput(input , strict)
print ("\n----------------8<----------------8<----------------\n")
print ("Input:\t" .. input)
-- default value
if strict == nil then strict = true end
-- nothing to do
if input == nil then return nil end
local working = input
local codecs_found = {}
local found_count = 0
local clean = false
while not clean do
clean = true
old = working
working = self.html_codec:Decode( working )
if old ~= working then
print ("Warning:\tINTRUSION DETECTED")
end
end
print ("Output:\t".. working)
return working
end
local default_encoder = DefaultEncoder:create()
default_encoder:Init()
default_encoder:TestInput("%25", true)
----------8<-----------8<--------------8<----------------
END OF FILE
Console Output:
tzury#1005:~/devel/lua$ lua problem.lua
----------------8<----------------8<----------------
Input: %25
nil
lua: problem.lua:70: attempt to index local 'pbs' (a nil value)
stack traceback:
problem.lua:70: in function 'DecodeCharacter'
problem.lua:54: in function 'Decode'
problem.lua:96: in function 'TestInput'
problem.lua:109: in main chunk
[C]: ?
In your code, the crash happens on this line:
local char = self.DecodeCharacter(pbs)
The problem is that you are calling DecodeCharacter with incorrect number of arguments.
Solution: call it like this (notice the colon):
local char = self:DecodeCharacter(pbs)
Explanation:
When you define functions in Lua using the colon (:), you are using a syntax sugar which hides an implicit first argument named self. Definitions like:
function HTMLEntityCodec:DecodeCharacter(pbs) ... end
Are actually 'translated' to this:
HTMLEntityCodec.DecodeCharacter = function (self, pbs) ... end
When you call the function, you either need to pass the self argument yourself, or use the colon call to supply it automatically. In your code (self.DecodeCharacter(pbs)), you are passing pbs which ends up as self in HTMLEntityCodec.DecodeCharacter, and pbs ends up being nil. Both following calls are equivalent and should solve the issue:
local char = self.DecodeCharacter(self, pbs)
local char = self:DecodeCharacter(pbs)

Scenes and groups trouble using Lua and Corona SDK

My buttons and scene changes are bugging, the buttons on my titlescreen scene bellow both work and direct to the appropriate screens, but they will only do it once. So I cannot naviagte to options, then back to the the title screen, then back to options again - and I cannot work out why?
Here is my titlescreen file:
module(..., package.seeall)
local assetPath = "assets/"
local mainGroup = display.newGroup()
function new()
local ui = require("ui")
local titleScreen = display.newImageRect(assetPath .. "mainMenu.png", display.contentWidth, display.contentHeight)
titleScreen.x = display.contentWidth / 2
titleScreen.y = display.contentHeight / 2
mainGroup:insert(titleScreen)
local onPlayTouch = function( event )
if event.phase == "release" then
director:changeScene("gameScreen")
end
end
local playButton = ui.newButton{
defaultSrc = assetPath .. "playnowbtn.png",
defaultX = 222,
defaultY = 62,
overSrc = assetPath .. "playnowbtn-over.png",
overX = 222,
overY = 62,
onEvent = onPlayTouch
}
playButton.x = display.contentWidth / 2
playButton.y = 50;
mainGroup:insert( playButton )
local onOptionTouch = function( event )
if event.phase == "release" then
director:changeScene("optionsScreen")
end
end
local optionButton = ui.newButton{
defaultSrc = assetPath .. "playnowbtn.png",
defaultX = 222,
defaultY = 62,
overSrc = assetPath .. "playnowbtn-over.png",
overX = 222,
overY = 62,
onEvent = onOptionTouch
}
optionButton.x = display.contentWidth / 2
optionButton.y = 190;
mainGroup:insert( optionButton )
return mainGroup
end
My options file looks like this :
module(..., package.seeall)
function new()
local assetPath = "assets/"
local localGroup = display.newGroup()
local background = display.newImage (assetPath .."optionsScreen.png")
localGroup:insert(background)
local onBackTouch = function( event )
if event.phase == "release" then
director:changeScene("titleScreen")
end
end
local backButton = ui.newButton{
defaultSrc = assetPath .. "playnowbtn.png",
defaultX = 222,
defaultY = 62,
overSrc = assetPath .. "playnowbtn-over.png",
overX = 222,
overY = 62,
onEvent = onBackTouch
}
backButton.x = display.contentWidth / 2
backButton.y = display.contentHeight / 2
localGroup:insert(backbutton)
return localGroup
end
Now the button is displayed on the options scene and responds to touch, but does not direct back to the titlescreen.
I think I am getting confused with groups and only assigning images to scenes not the whole game?
Can anyone help me out, Thanks.
EDIT:
I'm also getting these runtime errors when clicking the buttons.
Runtime error
/Users/Lewis/Desktop/proj/optionsScreen.lua:30: ERROR: table expected. If this is a function call, you might have used '.' instead of ':'
stack traceback:
[C]: ?
[C]: in function 'insert'
/Users/Lewis/Desktop/proj/optionsScreen.lua:30: in function 'new'
/Users/Lewis/Desktop/proj/director.lua:118: in function 'loadScene'
/Users/Lewis/Desktop/proj/director.lua:415: in function 'changeScene'
/Users/Lewis/Desktop/proj/titlescreen.lua:67: in function 'onEvent'
/Users/Lewis/Desktop/proj/ui.lua:94: in function
?: in function
Runtime error
/Users/Lewis/Desktop/proj/director.lua:151: attempt to call field 'unloadMe' (a nil value)
stack traceback:
[C]: in function 'unloadMe'
/Users/Lewis/Desktop/proj/director.lua:151: in function '_listener'
?: in function
?: in function
I don't use director.lua myself so I'm not 100% sure, but in your options.lua you put the following two lines inside the new() function:
local assetPath = "assets/"
local localGroup = display.newGroup()
However in your titlescreen.lua those lines are above the new() function, and I think that's how it needs to be.
In general you should make your indentation consistent, so that it's easy to notice which code is inside which code-blocks.
In your error print-out, it's asking for an unload me function.
Try adding this to your code (above the return statement) and see if it makes a difference:
function unloadMe()
print( "test" )
end
And see if that gets rid of the error. Another option is to ditch ui.lua and use the new widget library's widget.newButton() function instead. Here's the doc page for that (syntax is almost the same as what you already have, so shouldn't be much changes necessary):
http://developer.anscamobile.com/reference/index/widgetnewbutton

Resources