Error with ToString Function Output - function

"Arguments are of the wrong type, are out of acceptable range, or are in conflict with one another". This is the run-time error message I receive when I try to run the code below. I am using a class, clsReceipt, to formulate a receipt in the form of a string so I can output it in a rich edit for the user to view before proceeding to purchase the products (an overview of sorts). I cannot find any errors and thus I need help. Please bear in mind I am a high school student and have a somewhat limited knowledge. I am using Delphi XE3 on Windows.
Below is the code for btnPurchase:
procedure TfrmBuy.btnPurchaseClick(Sender: TObject);
var
i, n, itemNumber, quant : integer;
found: boolean;
begin
repeat
i := strtoint(inputbox('Purchase','Enter the number of items you wish to buy or enter 0 to cancel',''));
until i>=0;
if i <> 0 then
begin
for n := 1 to i do
begin
found := false;
repeat
itemnumber := strtoint(inputbox('Item selection','Enter the Item number of purchase no. ' + inttostr(n),''));
if dm.ADOtbl.Locate('Item number',itemnumber,[]) then
found := true
else
showmessage('The item number you enteres was not found. Please try again.');
until found = true;
repeat
quant := strtoint(inputbox('Quantity selection','Please enter the quantity of the item you wish to purchase','>0'));
until quant >0;
Myreciept := TReceipt.create(itemnumber,quant,n,i);
end;
richedit1.Lines.Clear;
richedit1.Lines.Add(myreciept.tostring);
btnCheckout.Visible := true;
showmessage('Below is the reciept of your purchase. If you are satisfied, proceed to checkoutby selecting "Confirm" or restart by selecting "Reset"');
end;
repeat
i := strtoint(inputbox('Purchase','Enter the number of items you wish to buy or enter 0 to cancel',''));
until i>=0;
if i <> 0 then
begin
for n := 1 to i do
begin
found := false;
repeat
itemnumber := strtoint(inputbox('Item selection','Enter the Item number of purchase no. ' + inttostr(n),''));
if dm.ADOtbl.Locate('Item number',itemnumber,[]) then
found := true
else
showmessage('The item number you enteres was not found. Please try again.');
until found = true;
repeat
quant := strtoint(inputbox('Quantity selection','Please enter the quantity of the item you wish to purchase','>0'));
until quant >0;
Myreciept := TReceipt.create(itemnumber,quant,n,i);
end;
richedit1.Lines.Clear;
richedit1.Lines.Add(myreciept.tostring);
btnCheckout.Visible := true;
showmessage('Below is the reciept of your purchase. If you are satisfied, proceed to checkoutby selecting "Confirm" or restart by selecting "Reset"');
end;
end;
Below is the code for the ToString function in the class:
function TReceipt.ToString: string;
var
k:integer;
begin
result := '';
result := 'Reciept' + #13 + '===============================================' + #13;
result := result + 'Order ID: ' + fOrderID + #13;
result := result + 'Item Name' + #9 + 'Quantity' + 'Cost' + #13;
for k := 1 to length(arrItemNo) do
begin
dm.ADOtbl.RecNo := arritemno[k];
result := result + dm.ADOtbl['Item Name'] + #9 + inttostr(arrQuantity[k]) + #9 + floattostrf((arrQuantity[k] * dm.ADOtbl['Price'] ),ffcurrency,5,2) + #13;
end;
result := result + #13 + #13 + 'Subtotal: ' + floattostrf(getsubtotal,ffcurrency,5,2) + #13;
result := result + 'VAT: ' + floattostrf(getVat,ffcurrency,5,2) + #13;
result := result + 'Grand Total: ' + floattostrf(ftotal,ffcurrency,5,2) + #13 + '===============================================';
end;
end.
If anyone could assist me with solving this problem that would be great.

(Other readers: Obviously this is a bit of a work in progress, because the OP
possibly needs more guidance than will fit in comments. Anyway ...)
In this case, as mentioned in earlier comments, the message is coming not from your app but from the MS ADO data access layer your app is calling into, by operations your code
is carrying out on the TADOxxx components in your project.
At the risk of stating the obvious, debugging + fixing a problem like this is usually
a multi step process of a) finding out where the error occurs, b) figuring out what is
causing it and c) fixing or working around it.
a) can be trickier, particularly for someone finding their feet, than it might sound
at first, but it does get easier with practice, and the debugger is very helpful in the way
it interacts with the IDE and the user to zero in on the error location.
First thing is get your project in best shape for debugging, for which your first stop is
Project | Options | Compiler. Turn Optimizations off, Stack Frames on, Use Debug DCUs on
and (if your code can run with it) Range Checking On. Go to Debugger Options in the IDE
(it has moved around since older versions like Delphi 7). In XE+ versions go to Tools | Options, scroll down to Debugger Options | Embarcadero Debuggers and check the box "Notify on language exceptions".
Next, do a full build of your project and then run it until the point where the error occurs. If the error manifests as an exception, that makes things easier - just run the app with F9 and the debugger will wrest control from it when the exception occurs. At this point, go to View | Debug Windows, Call Stack: where the exception occurred will be at the top of the window and is usually in the RTL or VCL source code, rather than your project's. Further down the list, you should see routines in your own code - the top one if those is the one you're after. Put a breakpoint at its entry point, dismiss the exception message(s) and go through the motions to
provoke the error again. This time, the debugger should stop on your breakpoint, and
single-stepping should take you to exactly where the error occurs.
Often, the cause of the problem is obvious, and you can fix it on the spot. If you can't,
that's the starting point for deciding which code should be in your SO question.
Before trying the above on your actual problem, have a quick practice by doing this. Add a button to your form and in its Click event, put "raise Exception.Create('I am an error');". Then compile + run the app and click the button.
For your real error, I'd start by placing a breakpoint on the first line below "begin" in your ToString function and just run the app until the b.point trips and single-step (F8) from there until you get to the line where the exception occurs. Then try again and this time trace into (F7) that line ...
"Arguments" in the sense the error message means are values being supplied for the parameter "place holders" that a routine, be it in your own code, or something it's calling into, is expecting to receive.
The arguments the error msg is referring to are data your app is trying to send through the ADO layer to the DB, usually as parameters or text originating from operations on your project's ADO components. So it's only likely to be statements where you do something with one of those objects that are the ones which could set the error off. Once you've found out where, we'll need some info to go into the q and probably most of the existing code can come out as not relevant.

Related

Memory leaks and JSON data

I have an app that reads a JSON data string from disk to create a string grid listing stocks (ticker, number held, cost) and then calls a stockbroker API to fill in current price and value. It works but the code below is causing memory leaks but whilst there are many internet posts on how to access data in a JSONArray none I could find discuss how to free allocated memory. Can anybody help ? I use Delphi Berlin 10.1 and Indy 10.6 if it matters. There are 3 pages of data, some stocks are on 2 pages, sTickers is a stringlist populated with each stock ticker (about 10 of them) and there are about 14 total stock holdings on the 3 stringgrids (tabGrids[0..2] which are on a page control.
The problem code is:
JSONArray := TJSONObject.ParseJSONValue(s) as TJSONArray;
if JSONarray = nil then
begin
ShowMessage('An error occurred reading the data file, section = [' +
iniSection[tabpage] + '].');
continue;
end;
for row := 0 to JSONArray.Count - 1 do
begin
s := (JSONArray.Items[row] as TJSONObject).Get('ticker').JSONValue.Value;
SL.Add(s);
end;
CombineStrings(sTickers, SL);
tabGrids[tabpage].RowCount := SL.Count + 2; //set row count
for row := 1 to SL.Count do
begin //add fixed data to each grid row
tabGrids[tabpage].Cells[0, row] := SL[row - 1];
tabGrids[tabpage].Cells[4, row] := (JSONArray.Items[row - 1] as TJSONObject).Get('qty').JSONValue.Value;
tabGrids[tabpage].Cells[6, row] := (JSONArray.Items[row - 1] as TJSONObject).Get('cost').JSONValue.Value;
tabGrids[tabpage].Cells[1, row] := (JSONArray.Items[row - 1] as TJSONObject).Get('name').JSONValue.Value;
if not tryStrToFloat(tabGrids[tabpage].Cells[4, row], qty) then qty := 0;
if not tryStrToFloat(tabGrids[tabpage].Cells[6, row], price) then price := 0;
tabGrids[tabpage].Cells[6, row] := FloatToStr(qty*price/100);
end;
tabGrids[tabpage].Width := tabGrids[tabpage].ColWidths[0] +
tabGrids[tabpage].ColWidths[1] + tabGrids[tabpage].ColWidths[2] +
tabGrids[tabpage].ColWidths[3] + tabGrids[tabpage].ColWidths[4] +
tabGrids[tabpage].ColWidths[5] + tabGrids[tabpage].ColWidths[6] + 18;
SL.Clear;
end;
JSONArray.Free;
I assume the (JSONArray.Items[row] as TJSONObject).Get('ticker').JSONValue.Value lines are allocating memory that I am not releasing but I do not see how to release it. Or maybe there is a better way to get the data.
You mention 3 pages of data. You are leaking 2 x TJasonArray, and you are freeing one TJasonArray on the last line right after an end; that doesn't have a corresponding begin.
From that I draw the conclusion that you have a loop (that you did not show) that you run three times. On each time you create a TJasonArray but you free only one, after the loop end;, Move the JSonArray.Free; to before the end;.
To do it simpler, you can just use a TJSONValue to parse and free it at end, without free array :
var
Value: TJsonValue
// ...
begin
Value := TJSONObject.ParseJSONValue(s);
try
Ar := Value.FindValue('item') as TJSONArray;
finally
FreeAndNil(Value);
end;
end;
Instead of :
tabGrids[tabpage].Cells[1, row] := (JSONArray.Items[row - 1] as TJSONObject).Get('name').JSONValue.Value;
You can do
tabGrids[tabpage].Cells[1, row] := JSONArray.Items[row - 1].GetValue<string>('name');
Then, you have a end; before you free the array, if it's a upper loop you will have a memory leaks. Use try finally block to free it and the TStringList.

How to use Nintegrate in mathematica whose integrand contains elements from a 1d array that need to be accessed by index

I am trying to evaluate the following integral:
where the issue lies with variables like F since it is defined as
F[x_, y_] := f[x, y]/(2*Cto[Norm[x]]*Cto[Norm[y]]) and Cto[x_] := C_t[[Round[x]]]
where C_t is a 1d array and x and y are two vector and I need to access the element of C_t corresponding to the integer of the magnitude of x for example. However, this gives me the following errors when evaluating the integral:
Ci = Flatten[Import["Downloads/ctjulien.txt", "table"]]
Cp = Flatten[Import["Downloads/clphiphi.txt", "table"]]
Subscript[C, t] = Flatten[Import["Downloads/ctobs.txt", "table"]]
Lp[a_] := 1052*{Cos[a], Sin[a]}
vL[L_] := {L, 0}
l[l1_, \[CapitalPhi]1_] :=
l1*{Cos[\[CapitalPhi]1], Sin[\[CapitalPhi]1]}
Cii[x_] := Ci[[Round[x]]]
f[x_, y_] := Cii[Norm[x]]*Dot[x + y, x] + Cii[Norm[y]]*Dot[x + y, y]
Cto[x_] := Subscript[C, t][[Round[x]]]
F[x_, y_] := f[x, y]/(2*Cto[Norm[x]]*Cto[Norm[y]])
Cpp[x_] := Cp[[Round[x]]]
NIntegrate[l1*F[l[l1,\[CapitalPhi]],{L,0}-l[l1,\[CapitalPhi]]]*F[Lp[\[CapitalPhi]p],{L,0}-Lp[\[CapitalPhi]p]]*(Dot[Lp[\[CapitalPhi]p],Lp[\[CapitalPhi]p]-l[l1,\[CapitalPhi]]]*If[Norm[Lp[\[CapitalPhi]p]-l[l1,\[CapitalPhi]]]<=2900,Cpp[Norm[Lp[\[CapitalPhi]p]-l[l1,\[CapitalPhi]]]],0]*f[-{L,0}+l[l1,\[CapitalPhi]],{L,0}-Lp[\[CapitalPhi]p]]+Dot[Lp[\[CapitalPhi]p],Lp[\[CapitalPhi]p]-l[{L,0}-l[l1,\[CapitalPhi]],\[CapitalPhi]]]*If[Norm[Lp[\[CapitalPhi]p]-l[{L,0}-l[l1,\[CapitalPhi]],\[CapitalPhi]]]<=2900,Cpp[Norm[Lp[\[CapitalPhi]p]-l[{L,0}-l[l1,\[CapitalPhi]],\[CapitalPhi]]]],0]*f[-l[l1,\[CapitalPhi]],{L,0}-Lp[\[CapitalPhi]p]]),{\[CapitalPhi],-Pi,Pi},{\[CapitalPhi]p,-Pi,Pi},{l1,2,3000}]
This isn't anywhere near an answer yet, but it is a start. Watch out for Subscript and greek characters and use those appropriately when you test this.
If you insert in front of your code
Ci =Table[RandomInteger[{1,10}],{3000}];
Cp =Table[RandomInteger[{1,10}],{3000}];
Ct =Table[RandomInteger[{1,10}],{3000}];
then you can try to test your code without having your data files present.
If you then test your code you get a stream of "The expression Round[Abs[2+L]] cannot be used as a part" but if you instead insert in front of your code L=2 or some other integer assignment then that error goes away
If you use NIntegrate[yourlongexpression...] then you get a stream of "Round[Sqrt[Abs[l1 Cos[phi]]^2+Abs[l1 Sin[phi]]^2 cannot be used as a part" If you instead use fun[phi_?NumericQ, phip_?NumericQ, l1_?NumericQ]:=yourlongexpression;
NIntegrate[fun[phi,phip,l1]...] then that error goes away.
If you use Table[fun[phi,phip,l1],{phi,-Pi,Pi,Pi/2},{phip,-Pi,Pi,Pi/2},{l1,2,10}] instead of your integral and you look carefully at the output then you should see the word List appearing a number of times. That means you have somelist[[0]] somewhere in your code and Mathematica subscripts all start with 1, not with 0 and that has to be tracked down and fixed.
That is probably the first three or four levels of errors that need to found and fixed.

scheduling services on startup

I have developed an Application using BDS 2006 which uses MySQL database(connected using DataModule and MyDAC components).
Now I want to start my application on the start-up of the system(Windows XP).So I included the application shortcut in the start up folder .
Now on the start-up, my application starts prior to the MySQL service getting started. Hence I get an error Cannot connect to MySQL.
So I inserted a blank from on start of my application and performed the check to see if MySQL is running or not.If not running then wait until it is running.
function ServiceGetStatus(sMachine, sService: PChar): DWORD;
{******************************************}
{*** Parameters: ***}
{*** sService: specifies the name of the service to open
{*** sMachine: specifies the name of the target computer
{*** ***}
{*** Return Values: ***}
{*** -1 = Error opening service ***}
{*** 1 = SERVICE_STOPPED ***}
{*** 2 = SERVICE_START_PENDING ***}
{*** 3 = SERVICE_STOP_PENDING ***}
{*** 4 = SERVICE_RUNNING ***}
{*** 5 = SERVICE_CONTINUE_PENDING ***}
{*** 6 = SERVICE_PAUSE_PENDING ***}
{*** 7 = SERVICE_PAUSED ***}
{******************************************}
var
SCManHandle, SvcHandle: SC_Handle;
SS: TServiceStatus;
dwStat: DWORD;
begin
dwStat := 0;
// Open service manager handle.
SCManHandle := OpenSCManager(sMachine, nil, SC_MANAGER_CONNECT);
if (SCManHandle > 0) then
begin
SvcHandle := OpenService(SCManHandle, sService, SERVICE_QUERY_STATUS);
// if Service installed
if (SvcHandle > 0) then
begin
// SS structure holds the service status (TServiceStatus);
if (QueryServiceStatus(SvcHandle, SS)) then
dwStat := ss.dwCurrentState;
CloseServiceHandle(SvcHandle);
end;
CloseServiceHandle(SCManHandle);
end;
Result := dwStat;
end;
code source
// if MySQL not running then sleep until its running
procedure TForm1.FormCreate(Sender: TObject);
begin
while(ServiceGetStatus(nil, 'MySQL5.5') <>4 ) do
begin
sleep (200);
end;
end;
I would like to know if my approach is correct? If not suggest the same.
Also can this be done without the programming by using windows?
Sleeping in the main thread is never a good idea.
It's better to do the waiting in a thread and post a message to the main thread when MySQL is running.
Answering the comment from #mghie:
Why would waiting on the event be any better (or any different) than calling Sleep()?
An event-driven GUI is considered good programming practice. There is no waiting involved.
When the event is fired, the GUI is informed about the status change of the database connection.
If you would be waiting in a Sleep() loop, the application appears non-responsive.
And calling Application.ProcessMessages to somewhat take care of that, is really not a good practice.
An example how to wait until MySQL is running in a thread:
const
WM_MySQL_READY = WM_USER + 1; // The unique message id
type
TForm1 = class(TForm)
...
private
procedure OnMySqlReady( var Msg: TMessage); message WM_MySQL_READY;
...
end;
In your thread:
Constructor TMyThread.Create( OwnerForm : TForm);
begin
Inherited Create( false);
FOwnerForm := OwnerForm; // Keep for later use
Self.FreeOnTerminate := true;
end;
procedure TMyThread.Execute;
var
SQL_started : boolean;
sleepEvent : TSimpleEvent;
begin
sleepEvent := TSimpleEvent.Create;
try
repeat
SQL_started := (ServiceGetStatus(nil, 'MySQL5.5') = 4);
sleepEvent.WaitFor(200); // Better than sleep();
until SQL_started or Terminated;
finally
sleepEvent.Free;
end;
// Inform main thread
PostMessage( FOwnerForm.Handle,WM_MySQL_READY,WPARAM(SQL_started),0);
end;
Ok, I misunderstood #mghie a little, his question was why the TSimpleEvent.WaitFor() is better than Sleep() inside the thread.
For a background see: thread-sleep-is-a-sign-of-a-poorly-designed-program.
In short, Sleep() puts the thread into a deep sleep and control is not given back at best periodic rate (if ever in some corner cases).
TSimpleEvent.WaitFor() on the other hand is much more responsive with regards to timing and waking up. (Remember that Windows is not a true real-time OS and timing is not guaranteed). Anyway rule of thumb, in threads, use TSimpleEvent.Waitfor() instead of Sleep().
Should need arise to halt the wait for connection to the MySQL server, some adjustment to the code can be made:
constructor TMyThread.Create(OwnerForm: TForm; cancelEvent : TSimpleEvent);
begin
inherited Create(false);
FOwnerForm := OwnerForm; // Make sure it's assigned
FCancelEvent := cancelEvent; // Make sure it's assigned
Self.FreeOnTerminate := true;
end;
procedure TMyThread.Execute;
var
SQL_started : boolean;
cancel : boolean;
begin
repeat
SQL_started := (ServiceGetStatus(nil, 'MySQL5.5') = 4);
cancel := (FCancelEvent.WaitFor(200) = wrSignaled);
until SQL_started or Terminated or cancel;
// Inform main thread
PostMessage( FOwnerForm.Handle,WM_MySQL_READY,WPARAM(SQL_started),0);
end;
To abort the thread prior to the connection is made, just call MyEvent.SetEvent.
You can even present a splash screen from a thread if you want to inform the user about what's going on during the wait.
See Peter Below's Threaded Splashscreen for Delphi for such an example. Note that this code does not make use of any VCL components or anything that involves synchronizing with the main thread.
You might also want to look at: Show a splash screen while a database connection (that might take a long time) runs.

TimeOutException and SerialPort in Delphi Prism

I need my program to catch TimeOutException every time SerialPort Read Times out, but it fails to do that. In fact, the program breaks when it goes to read and throws this exceptions, "The I/O operation has been aborted because of either a thread exit or an application request."
Here is how SerialPort Instantiated:
dxComm = class(System.Windows.Forms.Form)
private
protected
public
constructor;
serialPort1:System.IO.Ports.SerialPort;
thr:Thread;
method mythread;
end;
constructor DXComm;
begin
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
SerialPort1 := new System.Io.Ports.SerialPort();
thr:=nil;
end;
Here is how thread is created:
thr:= new Thread(#mythread);
thr.Start;
Here is the SerialPort settings:
case TypeDXCard.SelectedIndex of
0:
begin
DXProtocol := TDXProtocol.tDxTwo;
msglen := 6;
rmsglen := 5;
end;
1:
begin
DXProtocol := TDXProtocol.tDxExpress;
msglen:=0;
rmsglen:=0;
end;
else
begin
DXProtocol := TDXProtocol.tDxTwo;
msglen := 6;
rmsglen := 5;
end;
end;
dx := ord(DXProtocol);
if (SerialPort1 <> nil) then
begin
case CommPort.SelectedIndex of
0: SerialPort1.PortName := 'COM1';
1: SerialPort1.PortName := 'COM2';
2: SerialPort1.portName := 'COM3';
3: SerialPort1.PortName := 'COM4';
end;
case BaudRate.SelectedIndex of
0: SerialPort1.BaudRate := 1200;
1: SerialPort1.BaudRate := 2400;
2: SerialPort1.BaudRate := 4800;
3: SerialPort1.BaudRate := 9600;
4: SerialPort1.BaudRate := 19200;
5: SerialPort1.BaudRate := 38400;
6: SerialPort1.BaudRate := 57600;
7: SerialPort1.BaudRate := 115200;
end;
if (EvenParity.Checked) then
SerialPort1.Parity := System.IO.Ports.Parity.Even
else
SerialPort1.Parity := System.IO.Ports.Parity.None;
end;
with SerialPort1 do
begin
SerialPort1.DataBits:=8;
SerialPort1.DtrEnable:=true;
SerialPort1.ReadBufferSize:= 4096;
SerialPort1.ReadTimeout:=TimeOutDelay*2;
SerialPort1.RtsEnable:=true;
SerialPort1.StopBits:=System.IO.Ports.StopBits.One;
SerialPort1.WriteTimeout:=1000;
SerialPort1.Handshake := HandShake.None;
SerialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(#MySerialData);
end;
Here is my Thread that handles the SerialPort.Write:
method DXcomm.mythread;
var x,y:Integer;
begin
while true do
begin
Thread.Sleep(ScanTime);
SerialPort1.RtsEnable:=true;
SerialPort1.DiscardOutBuffer;
SendMessage; <---------Assembles the bytes and sends it out
while SerialPort1.BytesToWrite>0 do;
thread.Sleep(4);
SerialPort1.DiscardInBuffer;
SerialPort1.RtsEnable:=false;
if (stopthread) then
break;
end;
end;
Here is the event for reading bytes from the serialport:
method DXComm.MySerialData(sender: System.Object; e:SerialDataReceivedEventArgs);
begin
if not SerialPort1.IsOpen then Exit;
try
SerialPort1.Read(RXMsg,0,5); <------Here is Where my program throws that exception when I check on TimeOutException down below.
if changeFlag then
begin
changeList.IncRxCnt;
FixUpChangeList;
end
else
ActiveUnit.Retreive;
except on ex: TimeOutException do <----This line of code fails.
//except on ex: Exception do <----This line of code works fine, but executes all the time instead of just only when there is an exception.
begin
//TimeOut Exception
ActiveUnit.Timeout;
SerialPort1.DiscardInBuffer;
SerialPort1.DiscardOutBuffer;
end;
end;
end;
What am I doing wrong? I need to catch SerialPort.Read TimeOuts and take appropriate action.
It seems you're using the Serial port as a component on a form but doing the reading / writing in a background thread?
Or, as I got it, you write in a background thread and then read on some other, random, thread (the one that is calling the Event you react on).
That is a problem, because the background thread then (internally) want's to update the Serial Port 'Control', which isn't allowed from Background threads. The problem could also be that the thread waiting to read is interrupted by the other thread that is writing in the infinite loop and thus causes the I/O exception. It's a bit of guessing involved here.
First shot:
You have to either create the Serial Port dynamically (i.e. not putting it on your form but instanciating and configuring it by code) to prevent that or (strongly discouraged though), set System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls to false.
Second shot:
On the other hand I would strongly suggest to make definetly sure that only one thread at all is working with the serial port. Not writing in one thread and reading from another. Do everything that is related to this serial I/O in one single thread. Read OR write, but do not try to do both at the same time from different threads.
Instead of:
SerialPort1.Read(RXMsg,0,5);
Does Delphi have a serial function that returns the number of characters received and waiting to be read?
For example(in probably poor pseudo code):
while (Not Timeout)
{
if (serialport1.characterswaiting)
{
SerialPort1.Read(RXMsg,0,5);
}
}
I believe the problem lies in the fact that I am writing to the serialport in my own thread or user-defined thread and reading from the serialport in another. The event datareceived is part of the main thread of the program, I think.
As pointed out by Sebastian, it makes sense that writing and reading from the same thread should solve my serial communication problem. Indeed, it seems have to solved my serial communication, although it is little less than 100%. That's a timing issue, since my program depends on fixed time delays.
The steps: Within my thread, I write to the serial port and wait for sometime to read the response from the serialport. This seems to have greatly improved the communication, but now I don't wait for the datareceived event to fire once it sees something in the input buffer.
Correct me if I am wrong in my thinking or reasoning.

Passing variables into a function in Lua

I'm new to Lua, so (naturally) I got stuck at the first thing I tried to program. I'm working with an example script provided with the Corona Developer package. Here's a simplified version of the function (irrelevant material removed) I'm trying to call:
function new( imageSet, slideBackground, top, bottom )
function g:jumpToImage(num)
print(num)
local i = 0
print("jumpToImage")
print("#images", #images)
for i = 1, #images do
if i < num then
images[i].x = -screenW*.5;
elseif i > num then
images[i].x = screenW*1.5 + pad
else
images[i].x = screenW*.5 - pad
end
end
imgNum = num
initImage(imgNum)
end
end
If I try to call that function like this:
local test = slideView.new( myImages )
test.jumpToImage(2)
I get this error:
attempt to compare number with nil
at line 225. It would seem that "num" is not getting passed into the function. Why is this?
Where are you declaring g? You're adding a method to g, which doesn't exist (as a local). Then you're never returning g either. But most likely those were just copying errors or something. The real error is probably the notation that you're using to call test:jumpToImage.
You declare g:jumpToImage(num). That colon there means that the first argument should be treated as self. So really, your function is g.jumpToImage(self, num)
Later, you call it as test.jumpToImage(2). That makes the actual arguments of self be 2 and num be nil. What you want to do is test:jumpToImage(2). The colon there makes the expression expand to test.jumpToImage(test, 2)
Take a look at this page for an explanation of Lua's : syntax.