18.08.2016, 12:29
Hi, I used to play SA-MP 6+ years ago and am thinking of getting back into it + the scripting side. In my years since SA-MP i have coded entirely OOPy using mainly PHP, Java or Ruby, so it would be nice to have some sort of (limited) OOPiness in Pawn. I am also thinking about just using the Java plugin to code in.
I tried to make an OOP style using the define directives, but they're also kind of limited (or my knowledge is, I haven't touched Pawn in 6 years as I say). Anyway, if I could have your view on this code I would appreciate it.
I tried to make an OOP style using the define directives, but they're also kind of limited (or my knowledge is, I haven't touched Pawn in 6 years as I say). Anyway, if I could have your view on this code I would appreciate it.
PHP код:
#include <a_samp>
const MAX_STRING = 256;
new lastId;
stock _getNewClassObjectId(objectIds[], size) {
for(lastId = 0; lastId < size; lastId++) {
if(!objectIds[lastId]) {
objectIds[lastId] = true;
return lastId;
}
}
#if defined ThrowError
new string[MAX_STRING];
format(string, sizeof string, "Ran out of objects, max: %d", size);
ThrowError(string);
#endif
return -1;
}
stock _countInstances(objectIds[], size) {
new counter = 0;
for(new i = 0; i < size; i++) {
if(objectIds[i]) {
counter++;
}
}
return counter;
}
stock _getInstance(objectIds[], size, number) {
new counter = 0;
for(new i = 0; i < size; i++) {
if(objectIds[i]) {
if(counter == number) {
return i;
}
counter++;
}
}
return -1;
}
#define class(%0,%1) \
stock _%0_tag_check(%0:objid) { return int:objid; } \
new bool:_%0_objects[%1] = false
#define delete(%0,%1) _%0_objects[_%0_tag_check(%1)] = false
#define method(%0).%1(%2) _%0_%1(%0:this,%2)
#define methodb(%0).%1() _%0_%1(%0:this)
#define var(%0){%1} _%0_%1[sizeof _%0_objects]
#define val(%0){%1} _%0_%1[_%0_tag_check(this)]
#define callb(%0,%1).%2() _%0_%2(%1)
#define call(%0,%1).%2(%3) _%0_%2(%1, %3)
#define object(%0) %0:_getNewClassObjectId(_%0_objects, sizeof _%0_objects)
#define instances(%0) _countInstances(_%0_objects, sizeof _%0_objects)
#define instance(%0,%1) %0:_getInstance(_%0_objects, sizeof _%0_objects, %1)
class(User, 100);
new var(User){name}[MAX_STRING];
method(User).init(name[]) {
for(new i = 0; i < strlen(name); i++) {
val(User){name}[i] = name[i];
}
}
methodb(User).getName() {
return val(User){name};
}
main()
{
new User:u = object(User);
printf("User id: %d", int:u);
call(User, u).init("foo bar");
print(callb(User, u).getName());
printf("User instances: %d", instances(User)); // 1
delete(User, u);
printf("User instances: %d", instances(User)); // 0
}