How to use timer.performWithDelay with a method call - class

I'm using a Lua class to create two objects, each of which must check where the other is to determine their movement. I'm attempting to use timer.performWithDelay to have them check every second, but for some reason when I try to do this, the line
o.moveCheckTimer = timer.performWithDelay(1000, o:moveCheck, 0)
in the class constructor throws an error stating that "Function arguments are expected near ','".
I have attempted to use an anonymous function like this:
o.moveCheckTimer = timer.performWithDelay(1000, function() o:moveCheck() end, 0)
but that causes the timer of both objects to only call the function for the most recent object that was created and not for itself (also very confusing behavior, and if anyone knows why this happens I would love to learn why).
I have dug through the API and info on method calls thoroughly, but I can't seem to find anything that uses them both together, and I feel like I'm missing something.
How can I use the method call as the listener for this timer?
Here is the full constructor:
Melee = {}
Melee.__index = Melee
function Melee:new(id, name, lane, side)
local o = {}
setmetatable(o, Melee)
o.id = id
o.name = name
o.lane = lane
o.side = side
if name == "spearman" then
o.maxhp = 100
o.range = 1
o.damage = {10, 20}
o.imageName = "images/rebels/spearman.png"
else
error("Attempted to create melee unit with undefined name")
end
o.hp = o.maxhp
--Display self
o.image = display.newImageRect(mainGroup, "images/rebels/spearman.png", 80, 80)
o.image.x = 0
o.image.y = lanes[lane]
o.image.anchorY = 1
if side == 2 then
o.image.xScale = -1
o.image:setFillColor(0.8)
o.image.x = display.contentWidth - 100
end
--Move and attack
local destination = display.contentWidth
if side == 2 then
destination = 0
end
o.moving = 1
o.movement = transition.to(o.image, {x = destination, time = 30000+math.random(-200,200)})
o.moveCheckTimer = timer.performWithDelay(1000, o:moveCheck, 0)
--o.attackTimer = timer.performWithDelay(1000, self:attack, 0)
return o
end

Related

Mirth - iterate over insurance HL7 segments

working with an ADT message template in Mirth, having issues with the IN1 and IN2 segments, the IN2 specifically.
Here's a sample message that I'm working with, removed almost all the segments.
MSH|^~&|EPIC|AMB||99|20220403165344|RELEASEAUTO|ADT^A04|367476|T|2.5|||AL|NE
IN1|1|10500201|105^Test|BCBS NC BLUE CARE^Test1|PO BOX 35^^DURHAM^NC^27702^||
IN2|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||first iteration IN1-62||
IN1|1|10500201|106^Test|BCBS NC BLUE CARE^Test1|PO BOX 35^^DURHAM^NC^27702^||
IN2|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||second iteration IN1-62||
So far I've built the following to iterate over the IN1 segment:
//IN1 Segments
var IN1count=0;
for each (seg in msg.IN1) {
createSegment('IN1',output,IN1count);
output.IN1[IN1count]['IN1.2'] = seg['IN1.2'];
output.IN1[IN1count]['IN1.3'] = seg['IN1.3'];
output.IN1[IN1count]['IN1.4'] = seg['IN1.4'];
output.IN1[IN1count]['IN1.8'] = seg['IN1.8'];
output.IN1[IN1count]['IN1.9'] = seg['IN1.9'];
output.IN1[IN1count]['IN1.10'] = seg['IN1.10'];
output.IN1[IN1count]['IN1.12'] = seg['IN1.12'];
output.IN1[IN1count]['IN1.13'] = seg['IN1.13'];
output.IN1[IN1count]['IN1.22'] = seg['IN1.22'];
output.IN1[IN1count]['IN1.36'] = seg['IN1.36'];
IN1count++;
}
I'm struggling to map the IN2 segment correctly on the outbound, I've read about getSegmentsAfter but I can't find that function online... how do I write the correct JS code to look for whether the given IN1 has an IN2 after, specifically if it has IN2-61, and only then create the IN2 segment?
Hope that makes sense :)
You'll find code for createSegmentAfter here; it is JavaScript inserted before your transformer: https://github.com/nextgenhealthcare/connect/blob/2f3740db44c8d42aa6fafffd991b9c1fde940ea0/server/src/com/mirth/connect/server/builders/JavaScriptBuilder.java
One approach to keeping track of whether you just passed an IN1 would be to loop over all segments with something like this:
var was_in1 = false;
var last_in1;
for each ( seg in msg.children() ){
if (was_in1) {
if (seg.name() == "IN2") {
// existing IN2 follows IN1
} else {
// insert new IN2
}
if (seg.name() == "IN1") {
was_in1 = true;
last_in1 = seg;
} else {
was_in1 = false;
}
}
It'd be nice if there was a "nextSibling()" method for messages, but there isn't. Luckily, we can simulate it by:
Getting the current object's childIndex
Getting all children from the current object's parent
Access the next child with the index childIndex + 1
It'd look like this:
for each (seg in msg.IN1) {
// Do your IN1 stuff ...
var nextSeg = seg.parent().children()[ seg.childIndex() + 1];
if(nextSeg != null && nextSeg.name() == 'IN2' && nextSeg['IN2-61'].toString() != '') {
// Do yourIN2 stuff ...
}
}

Calling a custom function in Rasa Actions

I am facing a problem in developing a chatbot using rasa .
I am trying to call a custom function in rasa action file. But i am getting an error saying "name 'areThereAnyErrors' is not defined"
here is my action class. I want to call areThereAnyErrors function from run method. Could someone please help how to resolve this?
class ActionDayStatus(Action):
def areThereAnyErrors(procid):
errormessagecursor = connection.cursor()
errormessagecursor.execute(u"select count(*) from MT_PROSS_MEAGE where pro_id = :procid and msg_T = :messageT",{"procid": procid, "messageT": 'E'})
counts = errormessagecursor.fetchone()
errorCount = counts[0]
print("error count is {}".format(errorCount))
if errorCount == 0:
return False
else:
return True
def name(self):
return 'action_day_status'
def run(self, dispatcher, tracker, domain):
import cx_Oracle
import datetime
# Connect as user "hr" with password "welcome" to the "oraclepdb" service running on this computer.
conn_str = dbconnection
connection = cx_Oracle.connect(conn_str)
cursor = connection.cursor()
dateIndicator = tracker.get_slot('requiredDate')
delta = datetime.timedelta(days = 1)
now = datetime.datetime.now()
currentDate = (now - delta).strftime('%Y-%m-%d')
print(currentDate)
cursor = connection.cursor()
cursor.execute(u"select * from M_POCESS_FILE where CREATE_DATE >= TO_DATE(:createDate,'YYYY/MM/DD') fetch first 50 rows only",{"createDate":currentDate})
all_files = cursor.fetchall()
total_number_of_files = len(all_files)
print("total_number_of_files are {}".format(total_number_of_files))
Answer given by one of the intellectuals :
https://realpython.com/instance-class-and-static-methods-demystified/ Decide whether you want a static method or class method or instance method and call it appropriately . Also when you are using connection within the function it should be a member variable or passed to the method You dont have self as a parameter so you may be intending it as a static method - but you dont have it created as such

Finding object in a class by attribute value

How do you grab an object based on its attribute (in this case, an ID that is assigned to it)? Here is an example of the code that I'm currently working on.
Ped = {} -- Ped class.
Ped.__index = Ped
gPedID = 0
gPedAdditionalID = "Shop"
function Ped.create(_type, _skin, _x, _y, _z)
local _ped = {}
setmetatable(_ped,Ped)
_ped.oType = _type
_ped.pedElement = createPed(_skin, _x, _y, _z)
_ped.ID = gPedID
gPedID = gPedID + 1
return _ped
end
function pedID(player, command)
-- code to grab the object based on the object.ID
end
I've tried to make a table that references the object, i.e:
generictable[_ped.ID] = _ped
But to no avail, I'm guessing the reason why is because it only copies the address, not the actual reference.
Help is much appreciated, thanks!

attempt to index global 'physics' (a nil value)

I'm new with corona/lua and i'm i can't find a solution to this thing. I'm trying to spawn a object that fall from top to down and should stop at the bottom of the screen. Then i'll create the touch event etc etc..
but for now the problem is that i recieve this error:
attempt to index global 'physics' (a nil value)
and objects ofc doesn't fall down.
here is my code:
-----------------------------------------------------------------------------------------
--
-- main.lua
--
-----------------------------------------------------------------------------------------
local buttonY = display.contentWidth * 0.02
local buttonWidth = display.contentWidth * 0.1
local buttonHeight = display.contentWidth * 0.1
background = display.newImage("graphics/background.jpg")
local localGroup = display.newGroup()
local spawnTable = {}
function spawnLattina(params)
local object = display.newImage(params.image, params.buttonX,50);
object.objTable = params.objTable;
object.index = #object.objTable+1;
object.name = "object:".. object.index;
--fisica
if params.hasBody then
object.density = params.density or 0;
object.friction = params.friction or 0;
object.bounce = params.bounce or 0;
object.isSensor = params.isSensor or false;
object.bodyType = params.bodyType or "dynamic";
print(object.density .. " Friction: ".. object.friction .."bodyType: "..object.bodyType)
physics.addBody(object, object.bodyType,
{density = object.density,
friction = object.friction,
bounce = object.bounce}
)
end
object.group = params.group or nil
object.group:insert(object)
object.objTable[object.index] = object
return object
end
for i = 1, 2 do
local spawns = spawnLattina(
{
image = "graphics/lattina.png",
objTable = spawnTable,
buttonX = math.random(50,480),
hasBody = true,
density = 0,
friction = 12,
bodyType = "static",
group = localGroup,
}
)
end
You haven't started the physics engine. Write the following lines on the top of your class:
local physics = require "physics"
physics.start()
Keep Coding.................. :)

How to create a class, subclass and properties in Lua?

I'm having a hard time grokking classes in Lua. Fruitless googling led me to ideas about meta-tables, and implied that third-party libraries are necessary to simulate/write classes.
Here's a sample (just because I've noticed I get better answers when I provide sample code):
public class ElectronicDevice
{
protected bool _isOn;
public bool IsOn { get { return _isOn; } set { _isOn = value; } }
public void Reboot(){_isOn = false; ResetHardware();_isOn = true; }
}
public class Router : ElectronicDevice
{
}
public class Modem :ElectronicDevice
{
public void WarDialNeighborhood(string areaCode)
{
ElectronicDevice cisco = new Router();
cisco.Reboot();
Reboot();
if (_isOn)
StartDialing(areaCode);
}
}
Here is my first attempt to translate the above using the technique suggested by Javier.
I took the advice of RBerteig. However, invocations on derived classes still yield: "attempt to call method 'methodName' (a nil value)"
--Everything is a table
ElectronicDevice = {};
--Magic happens
mt = {__index=ElectronicDevice};
--This must be a constructor
function ElectronicDeviceFactory ()
-- Seems that the metatable holds the fields
return setmetatable ({isOn=true}, mt)
end
-- Simulate properties with get/set functions
function ElectronicDevice:getIsOn() return self.isOn end
function ElectronicDevice:setIsOn(value) self.isOn = value end
function ElectronicDevice:Reboot() self.isOn = false;
self:ResetHardware(); self.isOn = true; end
function ElectronicDevice:ResetHardware() print('resetting hardware...') end
Router = {};
mt_for_router = {__index=Router}
--Router inherits from ElectronicDevice
Router = setmetatable({},{__index=ElectronicDevice});
--Constructor for subclass, not sure if metatable is supposed to be different
function RouterFactory ()
return setmetatable ({},mt_for_router)
end
Modem ={};
mt_for_modem = {__index=Modem}
--Modem inherits from ElectronicDevice
Modem = setmetatable({},{__index=ElectronicDevice});
--Constructor for subclass, not sure if metatable is supposed to be different
function ModemFactory ()
return setmetatable ({},mt_for_modem)
end
function Modem:WarDialNeighborhood(areaCode)
cisco = RouterFactory();
--polymorphism
cisco.Reboot(); --Call reboot on a router
self.Reboot(); --Call reboot on a modem
if (self.isOn) then self:StartDialing(areaCode) end;
end
function Modem:StartDialing(areaCode)
print('now dialing all numbers in ' .. areaCode);
end
testDevice = ElectronicDeviceFactory();
print("The device is on? " .. (testDevice:getIsOn() and "yes" or "no") );
testDevice:Reboot(); --Ok
testRouter = RouterFactory();
testRouter:ResetHardware(); -- nil value
testModem = ModemFactory();
testModem:StartDialing('123'); -- nil value
Here's an example literal transcription of your code, with a helpful Class library that could be moved to another file.
This is by no means a canonical implementation of Class; feel free to define your object model however you like.
Class = {}
function Class:new(super)
local class, metatable, properties = {}, {}, {}
class.metatable = metatable
class.properties = properties
function metatable:__index(key)
local prop = properties[key]
if prop then
return prop.get(self)
elseif class[key] ~= nil then
return class[key]
elseif super then
return super.metatable.__index(self, key)
else
return nil
end
end
function metatable:__newindex(key, value)
local prop = properties[key]
if prop then
return prop.set(self, value)
elseif super then
return super.metatable.__newindex(self, key, value)
else
rawset(self, key, value)
end
end
function class:new(...)
local obj = setmetatable({}, self.metatable)
if obj.__new then
obj:__new(...)
end
return obj
end
return class
end
ElectronicDevice = Class:new()
function ElectronicDevice:__new()
self.isOn = false
end
ElectronicDevice.properties.isOn = {}
function ElectronicDevice.properties.isOn:get()
return self._isOn
end
function ElectronicDevice.properties.isOn:set(value)
self._isOn = value
end
function ElectronicDevice:Reboot()
self._isOn = false
self:ResetHardware()
self._isOn = true
end
Router = Class:new(ElectronicDevice)
Modem = Class:new(ElectronicDevice)
function Modem:WarDialNeighborhood(areaCode)
local cisco = Router:new()
cisco:Reboot()
self:Reboot()
if self._isOn then
self:StartDialing(areaCode)
end
end
If you were to stick to get/set methods for properties, you wouldn't need __index and __newindex functions, and could just have an __index table. In that case, the easiest way to simulate inheritance is something like this:
BaseClass = {}
BaseClass.index = {}
BaseClass.metatable = {__index = BaseClass.index}
DerivedClass = {}
DerivedClass.index = setmetatable({}, {__index = BaseClass.index})
DerivedClass.metatable = {__index = DerivedClass.index}
In other words, the derived class's __index table "inherits" the base class's __index table. This works because Lua, when delegating to an __index table, effectively repeats the lookup on it, so the __index table's metamethods are invoked.
Also, be wary about calling obj.Method(...) vs obj:Method(...). obj:Method(...) is syntactic sugar for obj.Method(obj, ...), and mixing up the two calls can produce unusual errors.
There are a number of ways you can do it but this is how I do (updated with a shot at inheritance):
function newRGB(r, g, b)
local rgb={
red = r;
green = g;
blue = b;
setRed = function(self, r)
self.red = r;
end;
setGreen = function(self, g)
self.green= g;
end;
setBlue = function(self, b)
self.blue= b;
end;
show = function(self)
print("red=",self.red," blue=",self.blue," green=",self.green);
end;
}
return rgb;
end
purple = newRGB(128, 0, 128);
purple:show();
purple:setRed(180);
purple:show();
---// Does this count as inheritance?
function newNamedRGB(name, r, g, b)
local nrgb = newRGB(r, g, b);
nrgb.__index = nrgb; ---// who is self?
nrgb.setName = function(self, n)
self.name = n;
end;
nrgb.show = function(self)
print(name,": red=",self.red," blue=",self.blue," green=",self.green);
end;
return nrgb;
end
orange = newNamedRGB("orange", 180, 180, 0);
orange:show();
orange:setGreen(128);
orange:show();
I don't implement private, protected, etc. although it is possible.
If you don't want to reinvent the wheel, there is a nice Lua library implementing several object models. It's called LOOP.
The way I liked to do it was by implementing a clone() function.
Note that this is for Lua 5.0. I think 5.1 has more built-in object oriented constructions.
clone = function(object, ...)
local ret = {}
-- clone base class
if type(object)=="table" then
for k,v in pairs(object) do
if type(v) == "table" then
v = clone(v)
end
-- don't clone functions, just inherit them
if type(v) ~= "function" then
-- mix in other objects.
ret[k] = v
end
end
end
-- set metatable to object
setmetatable(ret, { __index = object })
-- mix in tables
for _,class in ipairs(arg) do
for k,v in pairs(class) do
if type(v) == "table" then
v = clone(v)
end
-- mix in v.
ret[k] = v
end
end
return ret
end
You then define a class as a table:
Thing = {
a = 1,
b = 2,
foo = function(self, x)
print("total = ", self.a + self.b + x)
end
}
To instantiate it or to derive from it, you use clone() and you can override things by passing them in another table (or tables) as mix-ins
myThing = clone(Thing, { a = 5, b = 10 })
To call, you use the syntax :
myThing:foo(100);
That will print:
total = 115
To derive a sub-class, you basically define another prototype object:
BigThing = clone(Thing, {
-- and override stuff.
foo = function(self, x)
print("hello");
end
}
This method is REALLY simple, possibly too simple, but it worked well for my project.
It's really easy to do class-like OOP in Lua; just put all the 'methods' in the __index field of a metatable:
local myClassMethods = {}
local my_mt = {__index=myClassMethods}
function myClassMethods:func1 (x, y)
-- Do anything
self.x = x + y
self.y = y - x
end
............
function myClass ()
return setmetatable ({x=0,y=0}, my_mt)
Personally, I've never needed inheritance, so the above is enough for me. If it's not enough, you can set a metatable for the methods table:
local mySubClassMethods = setmetatable ({}, {__index=myClassMethods})
local my_mt = {__index=mySubClassMethods}
function mySubClassMethods:func2 (....)
-- Whatever
end
function mySubClass ()
return setmetatable ({....}, my_mt)
update:
There's an error in your updated code:
Router = {};
mt_for_router = {__index=Router}
--Router inherits from ElectronicDevice
Router = setmetatable({},{__index=ElectronicDevice});
Note that you initialize Router, and build mt_for_router from this; but then you reassign Router to a new table, while mt_for_router still points to the original Router.
Replace the Router={} with the Router = setmetatable({},{__index=ElectronicDevice}) (before the mt_for_router initialization).
Your updated code is wordy, but should work. Except, you have a typo that is breaking one of the metatables:
--Modem inherits from ElectronicDevice
Modem = setmetatable({},{__index,ElectronicDevice});
should read
--Modem inherits from ElectronicDevice
Modem = setmetatable({},{__index=ElectronicDevice});
The existing fragment made the Modem metatable be an array where the first element was almost certainly nil (the usual value of _G.__index unless you are using strict.lua or something similar) and the second element is ElectronicDevice.
The Lua Wiki description will make sense after you've grokked metatables a bit more. One thing that helps is to build a little infrastructure to make the usual patterns easier to get right.
I'd also recommend reading the chapter on OOP in PiL. You will want to re-read the chapters on tables and metatables too. Also, I've linked to the online copy of the 1st edition, but owning a copy of the 2nd is highly recommended. There is also a couple of articles in the Lua Gems book that relate. It, too, is recommended.
Another simple approach for subclass
local super = require("your base class")
local newclass = setmetatable( {}, {__index = super } )
local newclass_mt = { __index = newclass }
function newclass.new(...) -- constructor
local self = super.new(...)
return setmetatable( self, newclass_mt )
end
You still can use the functions from superclass even if overwritten
function newclass:dostuff(...)
super.dostuff(self,...)
-- more code here --
end
don't forget to use ONE dot when pass the self to the superclass function