Instance variable value in two objects of the same class (Objective C) - objective-c

I am new at Objective C and ay programmer's world in general (2 or 3 weeks). Also I am Italian, and so It's quite difficult for me using english and the right terminology.
I created a class: "Mano" (Hand) with its instances and methods: m1 and m2.
My question is: How can I do to read m1 variables value with m2 ?
m1 and m2 have for example "int a; a=0;"
then m1, executing a method, sets a = 10
how can m2 read m1's a? Becouse if m2 simply reads a it reads his own a ... a=0, right?
Sorry again but I don't know how to explain myself better than this!

This was meant to be a simple RPS (Rock Paper Scissors) game just to start learning a little Objective C programming. In the beginning there were two objects m1 and m2 as the “Computer hand m1” and the “Player hand m2”.
Of course as you can see i joined the two methods (computer random number and human number choosing) so that all de job is made by just one object.
When methods were splitted I had problems in the [verdetto] (game results) methods because of m2 (jn my case) were not able to get the right value of the object instance (i needed m1 values) …
and that’s why I asked you my question!
Here you have 0=Rock 1=Scissors 2=Paper
// File main.m
#import <Foundation/Foundation.h>
#import "mano.h"
int main(int argc, const char * argv[])
{
int contatore;
contatore = 1;
#autoreleasepool {
mano *m1;
m1 = [[ mano alloc ] init ];
// mano *m2;
// m2 = [[ mano alloc ] init ];
while (contatore <= 5) {
NSLog(#"\n Partita N. %d", contatore);
contatore++;
[m1 gioco];
[m1 controlloRisultato]; }
// [m1 generatoreRandom] RANDOM NUMBER GENERATOR to let the computer choose
// [m2 scelta numero]here the player was meant to choose bw 0,1,2.
[m1 verdetto]; //game results
}
return 0;
}
// File mano.h
#import <Foundation/Foundation.h>
#interface mano : NSObject {
NSArray *simboli; //Rock Scissors Paper
NSInteger casuale; // Random Number
NSInteger scelta; // Player Number
NSInteger computer; // CPU wins
NSInteger giocatore; // Player Wins
NSInteger pareggi; // Draws
}
- (void) gioco;
- (void) controlloRisultato;
- (void) verdetto;
// - (void) generatoreRandom
// - (void) scelta numero
#end
// File mano.m
#import "mano.h"
#implementation mano
- (id) init {
self = [super init];
casuale = 0;
scelta = 0;
simboli = [ [ NSArray alloc] initWithObjects: #"Sasso",#"Forbici",#"Carta", nil]; //questo va nella init, giustamente, altrimenti non vale per tutti i metodi.
return self; }
- (void) gioco {
scelta =0;
casuale =0;
casuale = arc4random_uniform(3); //il computer sceglie un numero
// L'utente fa la sua scelta qui sotto
do {
NSLog (#"\n \n Inserisci 0 per Sasso, 1 per Forbici, 2 per Carta");
scanf ("%ld", &scelta);
if (scelta >2 || scelta <0) NSLog (#" \n Hai inserito un numero NON VALIDO");
} while (scelta >2 || scelta <0);
}
- (void) controlloRisultato {
NSLog(#"\nIl computer ha scelto: %#", [simboli objectAtIndex:casuale]);
NSLog(#"\nTu hai scelto: %#", [simboli objectAtIndex:scelta ]);
switch (casuale) {
case (0):
if (scelta == 0) {
NSLog (#"\n È un pareggio!");
++pareggi;
break;}
else if (scelta == 1) {
NSLog (#"\n Il Computer Vince!");
++computer;
break;}
else if (scelta == 2) {
NSLog (#"\n Hai vinto!");
++giocatore;
break;}
case (1):
if (scelta == 0) {
NSLog (#"\n Hai Vinto!");
++giocatore;
break;}
else if (scelta == 1) {
NSLog (#"\n È un pareggio!");
++pareggi;
break;}
else if (scelta == 2) {
NSLog (#"\n Il computer Vince!");
++computer;
break; }
case (2):
if (scelta == 0) {
NSLog (#"\n Il computer Vince!");
++computer;
break; }
else if (scelta == 1) {
NSLog (#"\n Hai Vinto!");
++giocatore;
break; }
else if (scelta == 2) {
NSLog (#"\n È un pareggio");
++pareggi;
break;}
break;
default:
break;
}
}
- (void)verdetto {
NSLog(#"\n Vittorie giocatore: %ld", giocatore);
NSLog(#"\n Vittorie computer: %ld", computer);
NSLog(#"\n Pareggi: %ld", pareggi);
if (giocatore > computer) NSLog(#"\n Bravo! Hai vinto tu la partita!");
else NSLog(#"\n Hai perso! Il computer ha vinto la partita");
}
#end

Same as you would if they were not the same kind of object, basically. First, make what you want to read public:
// Hand.h
#import <Foundation/Foundation.h>
#interface Hand : NSObject
// Each hand maintains a value
#property (assign) int a;
// This makes it easy to show two Hands working together...not necesary
- (instancetype)initAsFirst:(BOOL)first;
#end
Then, use a reference to one object from inside the other:
// Hand.m
#import "Hand.h"
#implementation Hand
// To start, some other object will call this with first set to YES.
- (instancetype)initAsFirst:(BOOL)first
{
self = [super init];
if (self) {
if (first) {
// The first Hand will create a second one to demonstrate the difference.
self.a = 0;
[self showHands:[[Hand alloc] initAsFirst:NO]];
} else {
// The second Hand will have a different value to prove that it's different.
self.a = 10;
}
}
return self;
}
- (void)showHands:(Hand *)h
{
// Display both the value of this hand (first) and the one this hand created (second)
NSLog(#"Mine: %d, Other: %d", self.a, h.a);
}
#end

now I have 1 class
#interface mani : NSObject
that maybe could control the game result.
and 2 subclasses:
#interface computer : mani //for random number generator
#interface giocatore : mani //for player choosing number
Now the matter for me is letting the first class (mani) read its subclasses variables, and do what to do to determine who is the winner! Still can't get how it works, and belive me, I am reading forums, and e-books!

Related

Trouble with Polymorphism example from Programming in Objective-C, Stephen Kochan, 6th Edition (Program 9.1)

** UPDATE **
I have changed the extraneous division by zero error in the reduce method. This was not causing the problem.
Original Question Text
I am in the process of reading Stephen Kochan's book, Programming in Objective-C, 6th Edition. There is a program in Capter 9 (9.1) that demonstrates Polymorphism by having complex numbers and fraction each have a print method and an add method.
resultComplex = [c1 add: c2]
and
resultFraction = [f1 add: f2]
and likewise with the print methods. It is completely understandable to me but there appears to be a bust somewhere in the code and I was hoping someone could help. The book is excellent and previous chapters build on themselves with existing code. The earlier versions of the code have all worked. I am suspecting that I have done something stupid like mis-typed something but I've been pouring over it for a few hours.
The output is as follows:
Chapter_9[5617:303] 18 + 2.5i
Chapter_9[5617:303] +
Chapter_9[5617:303] -5 + 3.2i
Chapter_9[5617:303] -----------
Chapter_9[5617:303] 13 + 5.7i
Chapter_9[5617:303]
Chapter_9[5617:303] 1/10
Chapter_9[5617:303] +
Chapter_9[5617:303] 2/15
Chapter_9[5617:303] ------
(lldb)
The program is able to add the Complex numbers but dies at the point it is required to add the Fractions. Xcode identifies add method in Fraction as the offender the following line as the offensive point:
Fraction *result = [[Fraction alloc] init]; // must be alloc/init here
I will include the class files (.h and .m) for the Fraction class. I am leaving out the Complex class because that part of the code runs fine, although there is an analogous line in that Class that seems to work fine. If it is necessary, I will update the post to add those. I just didn't want to drown everyone with that code if my error is obvious.
UPDATE
I am inserting a picture of the debug and output
Fraction Header File
//
// Fraction.h
// Chapter_9
#import <Foundation/Foundation.h>
#interface Fraction : NSObject
#property int numerator, denominator;
-(void) print;
-(void) setTo: (int) n over: (int)d;
-(double) convertToNum;
-(Fraction *) add: (Fraction *) f;
-(void) reduce;
#end
Fraction Implementation File
//
// Fraction.m
// Chapter_9
#import "Fraction.h"
#implementation Fraction
#synthesize numerator, denominator;
-(void) print
{
NSLog (#"%i/%i", numerator, denominator);
}
-(double) convertToNum
{
if (denominator != 0)
return (double) numerator / denominator;
else
return NAN;
}
-(void) setTo: (int) n over: (int) d
{
numerator = n;
denominator = d;
}
-(void) reduce
{
int u = numerator;
int v= denominator;
int temp;
while (v!= 0) {
temp = u % v;
u = v;
v = temp;
numerator /= u;
denominator /=u; //originally there was an unrelated error here
}
}
-(Fraction *) add: (Fraction *) f
{
// To add two fractions:
// a/b + c/d = ((a*d) + (b*c) / (b*d)
// Store the answer in a new Fraction object called (result)
// ************* Here is where Xcode identifies the error *******************
Fraction *result = [[Fraction alloc] init]; // must be alloc/init here
result.numerator = numerator * f.denominator + denominator * f.numerator;
result.denominator = denominator * f.denominator;
[result reduce];
return result;
}
#end
Program Main File:
//
// main.m
// Chapter_9
// Programming in Objective-C, Stephen Kochan, 6th Edition
//Problem 9.1: Shared Method Names: Polymorphism
#import "Fraction.h"
#import "Complex.h"
int main(int argc, const char * argv[])
{
#autoreleasepool {
Fraction *f1 = [[Fraction alloc] init];
Fraction *f2 = [[Fraction alloc] init];
Fraction *fracResult;
Complex *c1 = [[Complex alloc] init];
Complex *c2 = [[Complex alloc] init];
Complex *compResult;
[f1 setTo: 1 over: 10];
[f2 setTo: 2 over: 15];
[c1 setReal: 18 andImaginary:2.5];
[c2 setReal: -5 andImaginary: 3.2];
//add and print 2 complex numbers
[c1 print]; NSLog(#" +"); [c2 print];
NSLog(#"-----------");
compResult = [c1 add: c2]; //compResult is alloc/init in add method
[compResult print];
NSLog(#"\n");
// add and print 2 fractions
[f1 print]; NSLog(#" +"); [f2 print];
NSLog(#"------");
// ******************** Here is where the method call takes place that causes the error
fracResult = [f1 add: f2]; //fracResult is alloc/init in add method
[fracResult print];
}
return 0;
}
I am obviously new to Xcode and Objective-C and so am not able to debug on my own. Sorry for the long and drawn out explanation. I hope someone can help.
Xcode should be giving you a fairly clear division-by-zero error in your reduce method. You haven't copied it correctly from the book, I'm guessing, because your division-by-zero error is being caused by an error in your GCD algorithm.
This:
while (v!= 0) {
temp = u % v;
u = v;
v = temp;
numerator /= u;
denominator /=v;
}
should be this:
while (v!= 0) {
temp = u % v;
u = v;
v = temp;
}
numerator /= u;
denominator /=u;

Trouble with NSString: using a controller to set an NSTextField?

I am using Xcode 4 writing a simple program to generate text based on user input. Im reading from two text fields successfully, but I am unable to send the result to a separate NSTextField. I'm confident I've made all the right connections in IB, and I'm sending the NSTextField the setStringValue method. I have created a ScaleGenerator object that I believe may be improperly creating the string itself. My Controller header looks like this:
#import <Cocoa/Cocoa.h>
#interface Controller : NSObject
{
IBOutlet NSTextField * notesField;
IBOutlet NSTextField * midiField;
IBOutlet NSTextField * resultField;
IBOutlet id scalegenerator;
}
- (IBAction) generate: (id) sender;
#end // Controller
The Controller implementation looks like this:
#import "Controller.h"
#import "ScaleGenerator.h"
#import <Foundation/foundation.h>
#implementation Controller
- (IBAction) generate: (id) sender
{
int midinote;
int notes;
NSString * scale;
midinote = [midiField intValue];
if(midinote < 0 || midinote > 127) {
NSRunAlertPanel(#"Bad MIDI", #"That MIDI note is out of range! (0 - 127)", #"OK", nil, nil);
return;
}
notes = [notesField intValue];
if(notes < 2 || notes > 24) {
NSRunAlertPanel(#"Bad Scale Size", #"You must have at least two notes in your scale, and no more than 25 notes!", #"OK", nil, nil);
return;
}
scale = [scalegenerator generateScale: midinote and: notes];
[resultField setStringValue:scale];
}
#end
My ScaleGenerator code looks like this:
#import "ScaleGenerator.h"
#import <math.h>
#implementation ScaleGenerator
- (NSMutableString *) generateScale: (int) midinote and: (int) numberOfNotes
{
double frequency, ratio;
double c0, c5;
double intervals[24];
int i;
NSMutableString * result;
/* calculate standard semitone ratio in order to map the midinotes */
ratio = pow(2.0, 1/12.0); // Frequency Mulitplier for one half-step
c5 = 220.0 * pow(ratio, 3); // Middle C is three semitones above A220
c0 = c5 * pow(0.5, 5); // Lowest MIDI note is 5 octaves below middle C
frequency = c0 * pow(ratio, midinote); // the first frequency is based off of my midinote
/* calculate ratio from notes and fill the frequency array */
ratio = pow(2.0, 1/numberOfNotes);
for(i = 0; i < numberOfNotes; i++) {
intervals[i] = frequency;
frequency *= ratio;
}
for(i = 0; i < n; i++){
[result appendFormat: #"#%d: %f", numberOfNotes + 1, intervals[i]];
}
return (result);
}
#end // ScaleGenerator
My ScaleGenerator object has one function, which is where I believe I may be messing things up. What kind of string can I iteratively append formatted text to?? And what method do I call??
You have not allocated/initialized your NSMutableString. Therefore the message appendFormat: goes to nil. Replace the line
NSMutableString * result;
with
NSMutableString * result = [[NSMutableString alloc] init];

SegmentedControl Always Zero

I am trying to build an application that rolls dice. Nothing fancy at all. However, I'm using a segmented control to determine the number of dice and the sides of the dice.
Here is the RollPressed code.
#import "DiceBrain.h"
#import "ViewController.h"
#interface ViewController ()
#property (readonly) DiceBrain *brain;
#end
#implementation ViewController
- (DiceBrain *) brain {
if (!brain) brain = [[DiceBrain alloc] init];
return brain;
}
- (IBAction)RollPressed:(id)sender {
int num_dice = dice.selectedSegmentIndex;
int num_sides = sides.selectedSegmentIndex;
NSLog(#"Number of Dice is %u and Number of Sides is %u", num_dice, num_sides);
int result = [self.brain RollDice:num_dice Sides: num_sides];
display.text = [NSString stringWithFormat:#"%g", result];
}
#end
According to NSLog there, I'm always using a zero. Of course, actuating using this logic to roll the dice results in the display showing me something like 3.82652e-308.
The logic used to roll the dice is
- (int)RollDice:(int)dice Sides:(int)num_sides{
total = 0;
for (int i = 0; i < dice; i++) {
total += (arc4random() % num_sides) + 1;
}
return total;
}
What could cause the segmented control to give me such funky results?
Sounds like your IBOutlets for sides and dice are not connected.
Check their value; it's probably NULL.

Trying to send a mouse click to a game window, mac

So I've been trying to use CGPostMouseEvent, and CGEventPostToPSN to send a mouse click to a mac game, and unfortunately have been very unsuccessful.
I was hoping someone may be able to help me think of this differently, or realize what I'm missing. Google hasn't been much help.
My guess is that it's because I'm trying to send a click event to a game window (openGL), vs. a normal window.
Here is another example of what I'm trying to send:
CGEventRef CGEvent;
NSEvent *customEvent;
NSPoint location;
location.x = 746;
location.y = 509;
customEvent = [NSEvent mouseEventWithType: NSLeftMouseDown
location: location
modifierFlags: NSLeftMouseDownMask
timestamp: time(NULL)
windowNumber: windowID
context: NULL
eventNumber: 0
clickCount: 1
pressure: 0];
CGEvent = [customEvent CGEvent];
CGEventPostToPSN(&psn, CGEvent);
Interestingly enough, I can move the mouse fine (CGDisplayMoveCursorToPoint(kCGDirectMainDisplay, clickPt);), I just can't send any clicks :/
Any help would be greatly appreciated.
Edit: Here is what is strange, once I move the mouse using CGDisplayMoveCursorToPoint, I actually have to physically move my mouse up or down a hair before I can even click, which is odd. The game doesn't accept any input unless I move it up/down (and the pointer then changes).
Thanks!
Well what you are try to build is "bot" or "robot" which basically sends commands in an orderly fashion to a game. Basically it will play for you as you are afk. This is great for games that force you to play to harvest minerals, commodities or whatever gives you money to advance in the game. Which is really kind of boring. I have successfully done this for a popular game, although i cannot mention the game as it breaks the user agreements which all these type of games have against "bots". So beware of what you are doing, as it may break your user agreement for many MMPG. But i post this successfully here because, the Mac has less bots available, none that i have been able to research, vs the PC which i have found many. So to level the playing field.. here is the code. I recommend to compile it as command line, and execute the macro in AppleScript (were the logic will reside on how to mimic the games click mouses, movements and send keys, basically your AI.
1.- First you need to run class that will get your psn "process serial number" which all games have. Basically what Thread it is running at. You can find out the name of the process in the utility in the Mac called "Activity Monitor". This can also be done easily in AppleScript.
Once you have the name, this class will locate and give you back its psn.
#import <Cocoa/Cocoa.h>
#include <Carbon/Carbon.h>
#include <stdio.h>
#interface gamePSN : NSObject
{
ProcessSerialNumber gamePSN;
ProcessInfoRec gameProcessInfo;
pid_t gameUnixPID;
}
- (ProcessSerialNumber) gamePSN;
- (ProcessInfoRec) gameProcessInfo;
- (pid_t) gameUnixPID;
- (void) getPSN;
#end
#implementation gameSN
- (ProcessSerialNumber) gamePSN { return gamePSN; }
- (ProcessInfoRec) gameProcessInfo { return gameProcessInfo; }
- (pid_t) gameUnixPID; { return gameUnixPID; }
- (void) getPSN
{
auto OSErr osErr = noErr;
auto OSErr otherErr = noErr;
auto ProcessSerialNumber process;
auto ProcessInfoRec procInfo;
auto Str255 procName;
auto FSSpec appFSSpec;
auto char cstrProcName[34];
auto char one ='G'; // FIRST CHARCTER OF GAME PROCESS NAME THESE NEED TO BE CHANGED AS I PUT IN FAKES
auto char two ='A'; // SECOND CHARACTER OF GAME PROCESS NAME THESE NEED TO BE CHANGED AS I PUT IN FAKES
auto char three = 'M'; // THIRD CHARACTER OF GAME PROCESS NAME THESE NEED TO BE CHANGED AS I PUT IN FAKES
auto unsigned int size;
process.highLongOfPSN = kNoProcess;
process.lowLongOfPSN = kNoProcess;
procInfo.processInfoLength = sizeof(ProcessInfoRec);
procInfo.processName = procName;
procInfo.processAppSpec = &appFSSpec;
while (procNotFound != (osErr = GetNextProcess(&process))) {
if (noErr == (osErr = GetProcessInformation(&process, &procInfo))) {
size = (unsigned int) procName[0];
memcpy(cstrProcName, procName + 1, size);
cstrProcName[size] = '\0';
// NEEDS TO MATCH THE SIGNATURE OF THE GAME..FIRST THREE LETTERS
// IF YOU CANT FIND IT WITH THE ACTIVITY MONITOR UTILITY OF APPLE MAC OS
// THEN RUN THIS SAME CLASS WITH AN NSLOG AND IT WILL LIST ALL YOUR RUNNING PROCESSES.
if ( (((char *) &procInfo.processSignature)[0]==one) &&
(((char *) &procInfo.processSignature)[1]==two) &&
(((char *) &procInfo.processSignature)[2]==three) &&
(((char *) &procInfo.processSignature)[3]==two))
{
gamePSN = process;
otherErr = GetProcessInformation(&gamePSN, &gameProcessInfo);
otherErr = GetProcessPID(&process, &gameUnixPID);
}
}
}
}
Once you have this process number it is easy to send key events as well as mouse events. Here is the mouse event clicks to send.
// mouseClicks.h
// ClickDep
// Created by AnonymousPlayer on 9/9/11.
#import <Foundation/Foundation.h>
#interface mouseClicks : NSObject
- (void) PostMouseEvent:(CGMouseButton) button eventType:(CGEventType) type fromPoint:(const CGPoint) point;
- (void) LeftClick:(const CGPoint) point;
- (void) RightClick:(const CGPoint) point;
- (void) doubleLeftClick:(const CGPoint) point;
- (void) doubleRightClick:(const CGPoint) point;
#end
/
// mouseClicks.m
// ClickDep
// Created by AnonymousPlayer on 9/9/11.v
#import "mouseClicks.h"
#implementation mouseClicks
- (id)init
{
self = [super init];
if (self) {
// Initialization code here if you need any.
}
return self;
}
- (void) PostMouseEvent:(CGMouseButton) button eventType:(CGEventType) type fromPoint:(const CGPoint) point;
{
CGEventRef theEvent = CGEventCreateMouseEvent(NULL, type, point, button);
CGEventSetType(theEvent, type);
CGEventPost(kCGHIDEventTap, theEvent);
CFRelease(theEvent);
}
- (void) LeftClick:(const CGPoint) point;
{
[self PostMouseEvent:kCGMouseButtonLeft eventType:kCGEventMouseMoved fromPoint:point];
NSLog(#"Click!");
[self PostMouseEvent:kCGMouseButtonLeft eventType:kCGEventLeftMouseDown fromPoint:point];
sleep(2);
[self PostMouseEvent:kCGMouseButtonLeft eventType:kCGEventLeftMouseUp fromPoint:point];
}
- (void) RightClick:(const CGPoint) point;
{
[self PostMouseEvent:kCGMouseButtonRight eventType:kCGEventMouseMoved fromPoint:point];
NSLog(#"Click Right");
[self PostMouseEvent:kCGMouseButtonRight eventType: kCGEventRightMouseDown fromPoint:point];
sleep(2);
[self PostMouseEvent:kCGMouseButtonRight eventType: kCGEventRightMouseUp fromPoint:point];
}
- (void) doubleLeftClick:(const CGPoint) point;
{
[self PostMouseEvent:kCGMouseButtonRight eventType:kCGEventMouseMoved fromPoint:point];
CGEventRef theEvent = CGEventCreateMouseEvent(NULL, kCGEventLeftMouseDown, point, kCGMouseButtonLeft);
CGEventPost(kCGHIDEventTap, theEvent);
sleep(2);
CGEventSetType(theEvent, kCGEventLeftMouseUp);
CGEventPost(kCGHIDEventTap, theEvent);
CGEventSetIntegerValueField(theEvent, kCGMouseEventClickState, 2);
CGEventSetType(theEvent, kCGEventLeftMouseDown);
CGEventPost(kCGHIDEventTap, theEvent);
sleep(2);
CGEventSetType(theEvent, kCGEventLeftMouseUp);
CGEventPost(kCGHIDEventTap, theEvent);
CFRelease(theEvent);
}
- (void) doubleRightClick:(const CGPoint) point;
{
[self PostMouseEvent:kCGMouseButtonRight eventType:kCGEventMouseMoved fromPoint:point];
CGEventRef theEvent = CGEventCreateMouseEvent(NULL, kCGEventLeftMouseDown, point, kCGMouseButtonRight);
CGEventPost(kCGHIDEventTap, theEvent);
sleep(2);
CGEventSetType(theEvent, kCGEventRightMouseUp);
CGEventPost(kCGHIDEventTap, theEvent);
CGEventSetIntegerValueField(theEvent, kCGMouseEventClickState, 2);
CGEventSetType(theEvent, kCGEventRightMouseDown);
CGEventPost(kCGHIDEventTap, theEvent);
sleep(2);
CGEventSetType(theEvent, kCGEventRightMouseUp);
CGEventPost(kCGHIDEventTap, theEvent);
CFRelease(theEvent);
}
#end
You may need to play with the sleep which is the time interval between pushing the mouse button and releasing it. I have found that using 1 second sometimes it does not do it. Putting 2 seconds make it work all the time.
So your main would to the following.
int main(int argc, char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSUserDefaults *args = [NSUserDefaults standardUserDefaults];
// Grabs command line arguments -x, -y, -clicks, -button
// and 1 for the click count and interval, 0 for button ie left.
int x = [args integerForKey:#"x"];
int y = [args integerForKey:#"y"];
int clicks = [args integerForKey:#"clicks"];
int button = [args integerForKey:#"button"];
//int interval= [args integerForKey:#"interval"];
int resultcode;
// PUT DEFAULT VALUES HERE WHEN SENT WITH EMPTY VALUES
/*if (x==0) {
x= 1728+66;
y= 89+80;
clicks=2;
button=0;
}
*/
// The data structure CGPoint represents a point in a two-dimensional
// coordinate system. Here, X and Y distance from upper left, in pixels.
CGPoint pt;
pt.x = x;
pt.y = y;
// Check CGEventPostToPSN Posts a Quartz event into the event stream for a specific application.
// only added the front lines plus changed null in Create Events to kCGHIDEventTap
gamePSN *gameData = [[gamePSN alloc] init];
[gameData getPSN];
ProcessSerialNumber psn = [gameData gamePSN];
resultcode = SetFrontProcess(&psn);
mouseClicks *mouseEvent =[[mouseClicks alloc] init];
if (button == 0)
{
if (clicks==1) {
[mouseEvent LeftClick:pt];
} else {
[mouseEvent doubleLeftClick:pt];
}
}
if (button == 1)
{
if (clicks==1) {
[mouseEvent RightClick:pt];
} else {
[mouseEvent doubleRightClick:pt];
}
}
[gameData release];
[mouseEvent release];
[pool drain];
return 0;
}
Hope this is helpful.... remember you can execute this in the terminal or in AppleScript by sending the following command.
do shell script "/...Path to Compiled Program.../ClickDep" & " -x " & someX & " -y " & someY & " -clicks 1 -button 1"
HAPPY GAMING!!!!

Lua and Objective C not running script

I am trying to create an objective c interface that encapsulates the functionality of storing and running a lua script (compiled or not.) My code for the script interface is as follows:
#import <Cocoa/Cocoa.h>
#import "Types.h"
#import "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#interface Script : NSObject<NSCoding> {
#public
s32 size;
s8* data;
BOOL done;
}
#property s32 size;
#property s8* data;
#property BOOL done;
- (id) initWithScript: (u8*)data andSize:(s32)size;
- (id) initFromFile: (const char*)file;
- (void) runWithState: (lua_State*)state;
- (void) encodeWithCoder: (NSCoder*)coder;
- (id) initWithCoder: (NSCoder*)coder;
#end
#import "Script.h"
#implementation Script
#synthesize size;
#synthesize data;
#synthesize done;
- (id) initWithScript: (s8*)d andSize:(s32)s
{
self = [super init];
self->size = s;
self->data = d;
return self;
}
- (id) initFromFile:(const char *)file
{
FILE* p;
p = fopen(file, "rb");
if(p == NULL) return [super init];
fseek(p, 0, SEEK_END);
s32 fs = ftell(p);
rewind(p);
u8* buffer = (u8*)malloc(fs);
fread(buffer, 1, fs, p);
fclose(p);
return [self initWithScript:buffer andSize:size];
}
- (void) runWithState: (lua_State*)state
{
if(luaL_loadbuffer(state, [self data], [self size], "Script") != 0)
{
NSLog(#"Error loading lua chunk.");
return;
}
lua_pcall(state, 0, LUA_MULTRET, 0);
}
- (void) encodeWithCoder: (NSCoder*)coder
{
[coder encodeInt: size forKey: #"Script.size"];
[coder encodeBytes:data length:size forKey:#"Script.data"];
}
- (id) initWithCoder: (NSCoder*)coder
{
self = [super init];
NSUInteger actualSize;
size = [coder decodeIntForKey: #"Script.size"];
data = [[coder decodeBytesForKey:#"Script.data" returnedLength:&actualSize] retain];
return self;
}
#end
Here is the main method:
#import "Script.h"
int main(int argc, char* argv[])
{
Script* script = [[Script alloc] initFromFile:"./test.lua"];
lua_State* state = luaL_newstate();
luaL_openlibs(state);
luaL_dostring(state, "print(_VERSION)");
[script runWithState:state];
luaL_dostring(state, "print(_VERSION)");
lua_close(state);
}
And the lua script is just:
print("O Hai World!")
Loading the file is correct, but I think it messes up at pcall.
Any Help is greatly appreciated.
Heading
Your code is so complex that there are no obvious faults. However, your next step should be to check the return value from lua_pcall. If it is nonzero, there will be an error message on the top of the stack which you can print via
fprintf(stderr, "Pcall failed: %s\n", lua_tostring(state, -1));
If you don't get a useful error message, my next step would be to dump the Lua stack. How many elements are on it? What is the (Lua) type of each element? What is the value. Functions lua_top, and luaL_typename will be useful. To print the value you will have to switch on the results of lua_type. Good luck.
I didn't run your code. But at first glance, I found that the signature of initWithScript: are different between header file (using u8*) and source file (using s8*).