Lua : timer.cancel --> 'Attempt to index a nil value' - timer

I'm fairly new to Lua, and one particular command in my code has been causing me some major problems.
I've been trying to cancel the timer:
currentPuddleDelay = timer.performWithDelay(puddleDelay, createPuddle);
The error that I am shown is:
Attempt to index a nil value
File: ?
stack traceback:
?: in function 'cancel'
game.lua:534: in function '?'
?: in function 'dispatchEvent'
?: in function '_saveSceneAndHide'
?: in function 'gotoScene'
game.lua:452: in function '?'
?: in function <?:182>
From what I've researched already, this problem can occur when the timer is within a function and is local, however, the timer in my code is global, so I don't think that that is the problem.
Below is the bit of code with the issue:
local function createPuddle()
local function constantDelay()
local puddle = display.newImage( sceneGroup, "images/puddle.png" )
puddle.x = puddleLane
puddle.y = -200
physics.addBody( puddle, "dynamic", {density=0, filter=puddleCollisionFilter} )
puddle:applyForce( 0, puddleSpeed, puddle.x, puddle.y )
sceneGroup:insert(3,puddle)
local function onPuddleCollision( self, event )
if ( event.phase == "began" ) then
print('puddle collision')
puddle:removeSelf( )
puddle = nil
composer.gotoScene( "menu" )
end
end
puddle.collision = onPuddleCollision
puddle:addEventListener( "collision" )
end
local constantDelayTimer = timer.performWithDelay(puddleDelay/2,constantDelay,1)
currentPuddleDelayHold = timer.performWithDelay(puddleDelay, createPuddle);
end
currentPuddleDelay = timer.performWithDelay(puddleDelay, createPuddle);
And then later on in the program:
timer.cancel(currentPuddleDelay)
Any help would be greatly appreciated.

I can only guess as you most likely did not provide all relevant code.
It obviously doesn't make sense to cancel a non-existing timer so for the start just do
if currentPuddleDelay then timer.cancel(currentPuddleDelay) end
If there is any reason why currentPuddleDelay should still exist you should find out why it is nil.

Related

Error: Can't Assign Function Call / Don't want to

It's friday and I'm tired and my brain obvs doesn't want to find this answer. Please help.
I want to assign the value to an array. It works in subsequent lines but not in one particular line, even though syntax seems the same to me? It seems to think I'm calling a function??
for entry in PROJECT:
i = i + 1
#A
if entry.startswith("A") :
ProjectA(i) = entry
#B
elif entry.startswith("B"):
ProjectB(i)= entry
#C
elif entry.startswith("C") :
ProjectC(i) = entry
# and Programme
elif entry.startswith("D") :
ProjectD(i) = entry
I'm told the problem is the last line: "ProjectD(i) = entry". Which to me seems like a replica of "ProjectC(i) = entry"
ProjectA(i) looks like you are calling a function; ProjectA[i] looks like an array element.

how to fetch value from an array and check its range in rails

I have included given code and its working fine
def check_ip
start = IPAddr.new(10.10.0.10).to_i
last = IPAddr.new(20.10.10.16).to_i
begin
ip_pool = IpPool.pluck(:start_ip, :end_ip)
# [["10.10.10.12", "10.10.10.15"], ["192.168.1.13", "192.168.1.13"]]
low = IPAddr.new("10.10.10.12").to_i
high = IPAddr.new("10.10.10.15").to_i
# it will check so on with ["192.168.1.13", "192.168.1.13"] values too
raise ArgumentError, I18n.t('errors.start') if ((low..high)===start or (low..high)===last
end
rescue ArgumentError => msg
self.errors.add(:start, msg)
return false
end
return true
end
Please guide me on how to implement this code without giving static value IPAddr.new("10.10.10.12").to_i I want to add values dynamically which I am fetching in ip_pool array so in low and high I am giving static values which are present in an array how could I give this values dynamically.
Since you have an array of low/high, you probably want to check all items in it:
begin
IpPool.pluck(:start_ip, :end_ip).each do |(low,high)|
raise ArgumentError, I18n.t('errors.start') \
if (low..high) === start || (low..high) === last
end
true
rescue ArgumentError => msg
self.errors.add(:start, msg)
false
end
Please note that I have the code a bit cleaned up:
removed superfluous returns;
corrected begin-rescue clause (there was a superfluous end right before rescue, that actually addressed rescue to the whole function body.

Lua/LOVE indexing problems

I'm getting a very irritating error whenever I do anything like this with arrays. I have code that sets up the array in the love.load() function:
function iceToolsInit()
objectArray = {} --for object handling
objectArrayLocation = 0
end
and then code that allows for the creation of an object. It basically grabs all of the info about said object and plugs it into an array.
function createObject(x, y, renderimage) --used in the load function
--objectArray is set up in the init function
objectArrayLocation = objectArrayLocation + 1
objectArray[objectArrayLocation] = {}
objectArray[objectArrayLocation]["X"] = x
objectArray[objectArrayLocation]["Y"] = y
objectArray[objectArrayLocation]["renderimage"] =
love.graphics.newImage(renderimage)
end
After this, an update function reads through the objectArray and renders the images accordingly:
function refreshObjects() --made for the update function
arrayLength = #objectArray
arraySearch = 0
while arraySearch <= arrayLength do
arraySearch = arraySearch + 1
renderX = objectArray[arraySearch]["X"]
renderY = objectArray[arraySearch]["Y"]
renderimage = objectArray[arraySearch]["renderimage"]
if movingLeft == true then --rotation for rightfacing images
renderRotation = 120
else
renderRotation = 0
end
love.graphics.draw(renderimage, renderX, renderY, renderRotation)
end
end
I of course clipped some unneeded code (just extra parameters in the array such as width and height) but you get the gist. When I set up this code to make one object and render it, I get this error:
attempt to index '?' (a nil value)
the line it points to is this line:
renderX = objectArray[arraySearch]["X"]
Does anyone know what's wrong here, and how I could prevent it in the future? I really need help with this.
It's off-by-one error:
arraySearch = 0
while arraySearch <= arrayLength do
arraySearch = arraySearch + 1
You run through the loop arrayLength+1 number of times, going through indexes 1..arrayLength+1. You want to go through the loop only arrayLength number of times with indexes 1..arrayLength. The solution is to change the condition to arraySearch < arrayLength.
Another (more Lua-ly way) is to write this as:
for arraySearch = 1, #objectArray do
Even more Lua-ly way is to use ipairs and table.field reference instead of (table["field"]):
function refreshObjects()
for _, el in ipairs(objectArray) do
love.graphics.draw(el.renderimage, el.X, el.Y, movingLeft and 120 or 0)
end
end
objectArray and movingLeft should probably be passed as parameters...

Construct dynamic timer with lua

I have created a timer called "timer", but I'm trying to create a function that will arm or disarm timer which is specified in it parameters
timer = sys.timer.create()
function MainTimer(timerName, action, time)
if action == "arm" then
timerName:arm(time)
else
timerName:disarm()
end
end
MainTimer("timer", "arm", 30)
but I'm getting an error from lua saying lua:272: attempt to call method 'arm' (a nil value)
where you think I did a mistake.
Thank you
Extra quotes :-)
MainTimer(timer, "arm", 30)

Creating a timer using Lua

I would like to create a timer using Lua, in a way that I could specify a callback function to be triggered after X seconds have passed.
What would be the best way to achieve this? ( I need to download some data from a webserver that will be parsed once or twice an hour )
Cheers.
If milisecond accuracy is not needed, you could just go for a coroutine solution, which you resume periodically, like at the end of your main loop, Like this:
require 'socket' -- for having a sleep function ( could also use os.execute(sleep 10))
timer = function (time)
local init = os.time()
local diff=os.difftime(os.time(),init)
while diff<time do
coroutine.yield(diff)
diff=os.difftime(os.time(),init)
end
print( 'Timer timed out at '..time..' seconds!')
end
co=coroutine.create(timer)
coroutine.resume(co,30) -- timer starts here!
while coroutine.status(co)~="dead" do
print("time passed",select(2,coroutine.resume(co)))
print('',coroutine.status(co))
socket.sleep(5)
end
This uses the sleep function in LuaSocket, you could use any other of the alternatives suggested on the Lua-users Wiki
Try lalarm, here:
http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/
Example (based on src/test.lua):
-- alarm([secs,[func]])
alarm(1, function() print(2) end); print(1)
Output:
1
2
If it's acceptable for you, you can try LuaNode. The following code sets a timer:
setInterval(function()
console.log("I run once a minute")
end, 60000)
process:loop()
use Script.SetTimer(interval, callbackFunction)
After reading this thread and others I decided to go with Luv lib. Here is my solution:
uv = require('luv') --luarocks install luv
function set_timeout(timeout, callback)
local timer = uv.new_timer()
local function ontimeout()
uv.timer_stop(timer)
uv.close(timer)
callback()
end
uv.timer_start(timer, timeout, 0, ontimeout)
return timer
end
set_timeout(1000, function() print('ok') end) -- time in ms
uv.run() --it will hold at this point until every timer have finished
On my Debian I've install lua-lgi packet to get access to the GObject based libraries.
The following code show you an usage demonstrating that you can use few asynchronuous callbacks:
local lgi = require 'lgi'
local GLib = lgi.GLib
-- Get the main loop object that handles all the events
local main_loop = GLib.MainLoop()
cnt = 0
function tictac()
cnt = cnt + 1
print("tic")
-- This callback will be called until the condition is true
return cnt < 10
end
-- Call tictac function every 2 senconds
GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, 2, tictac)
-- You can also use an anonymous function like that
GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, 1,
function()
print( "There have been ", cnt, "tic")
-- This callback will never stop
return true
end)
-- Once everything is setup, you can start the main loop
main_loop:run()
-- Next instructions will be still interpreted
print("Main loop is running")
You can find more documentation about LGI here

Resources