munk
2007-11-16 06:46:38
Logic and Efficiency - written by munk
1. INTRO
2. LOGIC
[INDENT]2.1 Understanding PRogramming and Language
2.2 Comments
2.3 Variables
2.4 Decisions
2.5 Operators
2.6 Loops and Arrays
2.7 Case Structures
2.8 Modules[/INDENT]
3. EFFICIENCY
[INDENT]3.1 Common Problems
3.2 Planning
3.3 Redundancy[/INDENT]
1. INTRO
This tutorial is for someone just starting out with programming. While I will be using SCAR for alot of my examples(considering where this is being posted), I will be explaining basic logic behind all languages, along with basic code efficiency.
2. LOGIC
2.1 Understanding PRogramming and Language
There are many different types of languages out there: design based(html,css), object-oriented(VB,C's), Data-oriented(database languages like SQL), etc. Most languages contain the same logic, the only thing that differes is the Syntax. Most people have heard this word, but for those who haven't, syntax is the actual structure and commands/functions in a particular language.
To further understand any language, you should learn how it is run. There are two general ways any code is run: Compiled or interpreted. I wont go into detail about both of these and just tell you the basic difference. When a language is compiled, all the code is run through before any of it is executed. When a language is interpreted, the code is executed line by line at runtime. As you may have guessed, SCAR is a compiler. All the code is checked before any of it is executed, and if there is an error in the code, the script will not run. To look further into how the code is run, you need to know what an Assembly Language is. Most any language you will write, will be the third layer. An assembly language is the second layer. The third layer is always designed for human eyes with syntax that has basic words and characters. Then it must be converted down to the second layer(assembly language) which looks more like something youd see in a cheesy 90's hacking movie, a bunch of random characters and numbers. You most likely will never even see an assembly language since it is all done internally, but it's nice to know what it is. Alright, if you haven't guessed what the first layer is already, it is machine code, or what's now known as binary. Im not gonna go into binary, mostly because you will never have to worry about it, but if you can divide by 2, then you can convert decimals to binary. Or if you are especially lazy(like me:D) you can actually convert decimals to binary on the basic Microsoft calculator(and hex too, I believe).
2.2 Comments
First Id like to explain that every language has whats called Comments. Some bunch of symbols that will indicate that anything after it will not be run as code. Comments are used for things like explaining what the code is doing(I will be doing this in my code throughout the tutorial), a programmer leaving notes for themselves, writing copyright/author information, removing a line of code or procedure that may be needed to put back in at which point you can just uncomment it. Most languages use the basic "//" for comments, but there are plenty of different ones out there.
2.3 Variables
I am going go over some basic terms that you should know. The first term would be Variable. A variable is nothing but a representation of information stored. All variables have a datatype. The basic datatypes being:
Integer - A whole number
Float - A number that may contain decimal places.
String - A collection of letters, numbers, and characters usually encapsed in quotes(single or double, depending on language)
Boolean - True/False
While there are many different datatypes throughout different languages, those are the basic ones you will see in almost every language. Some languages will require you to Declare(specify name and datatype) the variable before using it. But in some languages you are able to declare the variable in the Assignment. SCAR requires you to declare a variable before any assignments to it:
Math is a huge part of any language. If you are not good at math, then you might wanna brush up some basic math skills/terms before you try to write any language. Almost every language will have a calculator in the engine. Most actual code written, is derived from Math. Ill be explaining more about Math as I go on.
2.4 Decisions
Next are Decisions. Decisions are exactly what you think they are. They are the way to use variables to direct the script what to do. I won't go deep into types of decision's, because its boring, doesn't matter, and I dont feel like trying to explain what a clause is, so I will just say Condition. If your interested in what a clause is
http://en.wikipedia.org/wiki/Clause_%28logic%29
good luck;)
A condition is nothing but a boolean. The condition is checked to see if it is true. The most common decision is the If..then condition. In lamens, if this(condition) is true then do something. Heres thats in SCAR:
2.5 Operators
Now, time for Operators. This is one of those math things I was talkin about earlier. Operators are the same in programming as they are in math.
Now some special operators. And and Or, which do exactly what they mean. You can use these operators to test more than one condition in a single decision. "And" will test if both conditions are true, "Or" with test if either one of the conditions are true. Most languages will use the literal "And"/"Or", but some have special operators:
2.6 Loops and Arrays
So here we are at loops. Loops combined with arrays are a programmers best friend. I will explain arrays later, but right now lets take a look into loops. There are so many kinds of loops, usually more than 3 a language, and they all depend on the syntax of the language. SCAR contains most of normal loop types, so Ill focus on it's syntax. One that is in SCAR that I havent seen in that many other languages is Repeat..Until. This will repeat the encapsed code until the condition specified is true. For example:
Now this is where arrays come in. An array is a datatype that stores a series of variables of a datatype.
Since I knew the length of the array, I just set the end number, but if you dont know the length of the array, you can create a variable that is equal to length(array)-1. For more on this, consult a tutorial with a full SCAR array explanation.
2.7 Case Structures
Alright, so a decision is a boolean, that's all fine and dandy, but what if you want a decision that has more than two(true/false) outcomes. Thats where a case structure comes in handy. Most languages have a case structure, while syntax may be slightly different, the general idea is always the same. A basic case structure in SCAR:
2.8 Modules
One of the most important parts of any language are Modules. You might know these as Functions,Methods,sub-routines, or Procedures. I have always said functions because they work exactly like functions in Math. If you have a solid understand of math functions, you will understand Modules very easily. in math, a function is represented
3. EFFICIENCY
3.1 Common Problems
Keeping code efficient is a big part of any language. Too much uneccessary code can yield bad results. For one, when code gets excessive and messy, it can get hard to edit and cause confusion in the programmer. This can lead to Ghosts. Simply put, ghosts are pieces of code that are formed from half removed pieces of code, along with lines that may not be needed but havent been removed. Ghosts can run unnecessary commands that can take up memory, or even cause wierd results or errors. Along with this comes the term Spaghetti Code. I always thought that was a funny name for it, but spaghetti code is exactly what it sounds like: when your code is all tangled up in itself like spaghetti. This can cause insufficient use of memory, errors, or even memory leaks. Using SCAR, you wont have to worry to much about spaghetti code, since SCAR is single threaded, and since its compiled all errors will be caught before running.
3.2 Planning
Making an efficient script is all about planning. You need to think about what you are going to create. Think about all the methods you want to use to do what you want. Always plan for upgradeability later. You dont want to finish something, and then a week later have to rewrite the whole idea because you need to add something important. The best idea, if you really want to plan out your code, is to use a flowchart. A flowchart is a drawing depicting how a program/script will work. I, myself, do not usually draw out a flowchart, but I create one in my head days before I start writing any code. to learn more about flowcharts visit:
http://en.wikipedia.org/wiki/Flowchart
3.3 Redundancy
Since I am not talking about database languages, we do not need to worry about Redundancy that much, but I'll skim over it in terms of how to reduce it in scripts. Redundancy is unnecessary repetitiveness. The best way to reduce redundancy in a script, is to do what I mentioned earlier. Create a custom function to run certain commands, so you can call the single function, instead of calling all the commands.
the more you know.
1. INTRO
2. LOGIC
[INDENT]2.1 Understanding PRogramming and Language
2.2 Comments
2.3 Variables
2.4 Decisions
2.5 Operators
2.6 Loops and Arrays
2.7 Case Structures
2.8 Modules[/INDENT]
3. EFFICIENCY
[INDENT]3.1 Common Problems
3.2 Planning
3.3 Redundancy[/INDENT]
1. INTRO
This tutorial is for someone just starting out with programming. While I will be using SCAR for alot of my examples(considering where this is being posted), I will be explaining basic logic behind all languages, along with basic code efficiency.
2. LOGIC
2.1 Understanding PRogramming and Language
There are many different types of languages out there: design based(html,css), object-oriented(VB,C's), Data-oriented(database languages like SQL), etc. Most languages contain the same logic, the only thing that differes is the Syntax. Most people have heard this word, but for those who haven't, syntax is the actual structure and commands/functions in a particular language.
To further understand any language, you should learn how it is run. There are two general ways any code is run: Compiled or interpreted. I wont go into detail about both of these and just tell you the basic difference. When a language is compiled, all the code is run through before any of it is executed. When a language is interpreted, the code is executed line by line at runtime. As you may have guessed, SCAR is a compiler. All the code is checked before any of it is executed, and if there is an error in the code, the script will not run. To look further into how the code is run, you need to know what an Assembly Language is. Most any language you will write, will be the third layer. An assembly language is the second layer. The third layer is always designed for human eyes with syntax that has basic words and characters. Then it must be converted down to the second layer(assembly language) which looks more like something youd see in a cheesy 90's hacking movie, a bunch of random characters and numbers. You most likely will never even see an assembly language since it is all done internally, but it's nice to know what it is. Alright, if you haven't guessed what the first layer is already, it is machine code, or what's now known as binary. Im not gonna go into binary, mostly because you will never have to worry about it, but if you can divide by 2, then you can convert decimals to binary. Or if you are especially lazy(like me:D) you can actually convert decimals to binary on the basic Microsoft calculator(and hex too, I believe).
2.2 Comments
First Id like to explain that every language has whats called Comments. Some bunch of symbols that will indicate that anything after it will not be run as code. Comments are used for things like explaining what the code is doing(I will be doing this in my code throughout the tutorial), a programmer leaving notes for themselves, writing copyright/author information, removing a line of code or procedure that may be needed to put back in at which point you can just uncomment it. Most languages use the basic "//" for comments, but there are plenty of different ones out there.
2.3 Variables
I am going go over some basic terms that you should know. The first term would be Variable. A variable is nothing but a representation of information stored. All variables have a datatype. The basic datatypes being:
Integer - A whole number
Float - A number that may contain decimal places.
String - A collection of letters, numbers, and characters usually encapsed in quotes(single or double, depending on language)
Boolean - True/False
While there are many different datatypes throughout different languages, those are the basic ones you will see in almost every language. Some languages will require you to Declare(specify name and datatype) the variable before using it. But in some languages you are able to declare the variable in the Assignment. SCAR requires you to declare a variable before any assignments to it:
var
i:integer; //declaring
begin
i:=0; //assignment
end;
While PHP would be:
$i = 0; //declared in the assignment
PHP is also nice enough to figure out the datatype for you:) It all depends on the language. Both of the above examples declare an integer variable named "i" and then set it equal to 0. I hope by now you have some understanding of variables. If not, bust out a math book and go to town;) Math is a huge part of any language. If you are not good at math, then you might wanna brush up some basic math skills/terms before you try to write any language. Almost every language will have a calculator in the engine. Most actual code written, is derived from Math. Ill be explaining more about Math as I go on.
2.4 Decisions
Next are Decisions. Decisions are exactly what you think they are. They are the way to use variables to direct the script what to do. I won't go deep into types of decision's, because its boring, doesn't matter, and I dont feel like trying to explain what a clause is, so I will just say Condition. If your interested in what a clause is
http://en.wikipedia.org/wiki/Clause_%28logic%29
good luck;)
A condition is nothing but a boolean. The condition is checked to see if it is true. The most common decision is the If..then condition. In lamens, if this(condition) is true then do something. Heres thats in SCAR:
if condition then
begin
doSomething;
end;
And heres some fun actionscript that reiterates the ideas Ive gone over.
var bool:boolean=true; //declare and assign
if bool {
trace('this is horribly redundant!'); // output
}
haha…made me laugh. If you can understand that, then you're doing great.2.5 Operators
Now, time for Operators. This is one of those math things I was talkin about earlier. Operators are the same in programming as they are in math.
= equals
< less than
> greater than
<= less than or equal to
>= greater than or equal to
You can use the operators to create conditions for decisions with integers and integer variables. A basic equals example in SCAR:
var
r:integer; //declare variable
begin
r:=random(10); // assign random number to variable
if r=5 then writeln('whatre the odds!!'); // if the random number equals 5 then output
end;
The equals operator can also be used to compare String variables. Now before you look at the next example I should explain that in most languages, the Assignment and Equals Operator are usually different. In the above example(SCAR), the assignment uses ":=" and the condition uses "=". The next example is showing a string comparison in PHP
$str = 'a string!'; // declare and assign string
if ($str == '!not a string') { //condition, in this case will be false
echo $str;
}
As you can see, in PHP, the assignment is "=" and the equals operator is "==". Different languages use different combination of the two. In most languages, like PHP, where the equals operator is "==", you can also use a special "===" for strict testing(tests if the same datatype, as well as same data). As mundane as that may sound, it can come in handy. Quick example in PHP(not sure if this is true in PHP5)
if (0 == false) { // This returns true
if (0 === false) { // This returns false
now that brings me to uh….aww crap, I forgot the word. Basically, Not Equal. Testing the condition for a false instead of true. In SCAR its quite simple:
if not(chos) then eat; //mmmmm, nachos
Just put a "not" before the condition. This will check is the boolean variable "chos" is false, instead of the normal true. Other languages use ! denotation.
if ($var!=1) { //Takes place of first equals sign
if (!$var==1) { //before the whole condition
those will both check if the variable "$var" is not equal to 1. Along with this you can use an else to catch if a decision is returned false. You can use else when you want to execute something if the condition is true, and execute something else if the condition is false. In SCAR:
If condition then
writeln('condition was true!');
else
writeln('condition was false');
Every language contains an "else" and most of the time, the syntax is the literal use of the word "else". Makes it easy;)Now some special operators. And and Or, which do exactly what they mean. You can use these operators to test more than one condition in a single decision. "And" will test if both conditions are true, "Or" with test if either one of the conditions are true. Most languages will use the literal "And"/"Or", but some have special operators:
if (this && thisToo) { // && is the same as "and"
if (this || maybeThis) { // || is the same as "or"
An alternative to these operators, and another common programming term, is Nesting. In this case, I'll just do a quick explanation of nested decisions. A nested decision is a decision that is based on another decision because its "nested" inside of it. I use it all the time in SCAR. A good example is most autocolor functions will run atleast 2 nested decisions.
if (h>9) and (h<14) then // initial decision
if (s>46) and (s<65) then // first nested decision
if (l>12) and (l<27) then exit; // second nested decision
2.6 Loops and Arrays
So here we are at loops. Loops combined with arrays are a programmers best friend. I will explain arrays later, but right now lets take a look into loops. There are so many kinds of loops, usually more than 3 a language, and they all depend on the syntax of the language. SCAR contains most of normal loop types, so Ill focus on it's syntax. One that is in SCAR that I havent seen in that many other languages is Repeat..Until. This will repeat the encapsed code until the condition specified is true. For example:
repeat
actions;
//failsafe check
until(condition);
A similar one in other languages would be
do {
actions;
//failsafe check
until(condition); //do actions until condition is true
do {
actions;
//failsafe check
while(condition); //do actions while condition is true
I dont think Ive ever used Repeat before SCAR. The most common loop is the While..do. Here is the basic SCAR example:
while(thisIsTrue)do
begin
actions;
//failsafe check
end;
As you may have noticed, You should always include a Failsafe in a loop. A failsafe is just a variable that will break the loop after a certain amount of loops or time. The problem with loops are…well, that they loop. If the condition is never reachable a loop will loop forever, often causing an application/system crash. This is called Recursion. While most recursion is considered bad, it is the essential part of my favorite thing about math, Fractals. Fractals are basically designs made by recurring math expressions. I am not a big math buff, but if you have some extra time read about fractals, The Mandelbrot Set, and the Chaos Theory. But anywho, to stop the bad type of recursion, there is For loops. "For" loops will let you specify a number of Iterations(number of times it loops). In SCAR the "for" loop is better known as "For..To..Do", and an iteration count variable needs to be declared.
var
i:integer;
begin
for i:=0 to 10 do
begin
writeln(inttostr(i));
end;
end;
The above code will loop through 10 times incrementing the variable "i" each time and writing it to the debug box. For loops will change from language to language, but the idea is generally the same, create an iteration variable that increments to a certain point. Heres an example from actionscript and I think VB too(please correct me if im wrong)
for(var i=0;i>10;i=i+1) {
actions;
}
The above sets the variable "i" to 0, ends when "i" is greater than 10, and after every loop will make "i" equal to "i" plus 1(increment). This adds the option to make custom increment values, and different operators for the end statement(the above used greater than).Now this is where arrays come in. An array is a datatype that stores a series of variables of a datatype.
var
theArray:array of integer; // declare an array of integer variables
begin
setArrayLength(theArray,3); // set the length of the array(in this case, 3)
theArray[0]:=4; // an array always starts at 0.
theArray[1]:=2; // arrays use brackets to define which of the array
theArray[2]:=0; // variables it uses.
end;
They are extremely useful when you have alot of common data that you need to store and maybe run through several times. That's where the iteration variable comes in handy.
var
i:integer; // iteration variable
strArr:array[0..2] of String; // [0..2] declares the length so I dont have to later
begin
strArr[0]:='A'; // set the array variables
strArr[1]:='String';
strArr[2]:='Array';
for i:=0 to 2 do // for loop
begin
writeln(strArr[i]); // output
end;
end;
the above will output:
A
String
Array
Since I knew the length of the array, I just set the end number, but if you dont know the length of the array, you can create a variable that is equal to length(array)-1. For more on this, consult a tutorial with a full SCAR array explanation.
2.7 Case Structures
Alright, so a decision is a boolean, that's all fine and dandy, but what if you want a decision that has more than two(true/false) outcomes. Thats where a case structure comes in handy. Most languages have a case structure, while syntax may be slightly different, the general idea is always the same. A basic case structure in SCAR:
case varOrModule of
0: writeln('the varOrModule was 0');
1: writeln('the varOrModule was 1');
2: writeln('the varOrModule was 2');
else writeln('did not match varOrModule'); // You can use 'else' to catch if its missed
end;
The SCAR case structure is very similiar to those you will see in modern day language. The only other I can think of, would be something like PHP.
switch($varOrModule) { // the word switch instead of case
0: echo "varOrModule was 0";
1: echo "varOrModule was 1";
2: echo "varOrModule was 2";
} else {echo "no match";}
Case structures are also good for running through functions. I put them after the loops section for this reason. Using the iteration variable of a loop, you can loop through a case structure. A perfect example, is the the great, but now Deprecated(out of date code), FindFastRandoms by WT-Fakawi. I am sure everyone here has seen it atleast once, but it is the perfect example so here it is.
function FindFastRandoms: Boolean; //By WT-Fakawi.
var
i: Integer;
begin
for i := 1 to 9 do
begin
case I of
1: if FindDead then
Result := True;
2: if FindMod then
Result := True;
3: if FindMime then
Result := True;
4: if FindMaze then
Result := True;
5: if FindQuiz then
Result := True;
6: if FindDemon then
Result := True;
7: begin
if NoGameTab then
begin
Result := True;
Players[CurrentPlayer].loc := 'No GameTab';
Logout;
Exit;
end;
end;
8: begin
if InBlack then
begin
Result := True;
Players[CurrentPlayer].loc := 'InBlack';
Logout;
Exit;
end;
end;
9: RC;
end;
wait(1);
end;
end;
The iteration variable is used as the variable for the case structure so that each case is run once. 2.8 Modules
One of the most important parts of any language are Modules. You might know these as Functions,Methods,sub-routines, or Procedures. I have always said functions because they work exactly like functions in Math. If you have a solid understand of math functions, you will understand Modules very easily. in math, a function is represented
f(x)
"f" is the function name, and "x" is the variable. A math function will also have an expression, something like:
f(x)=2x+1
That is the full function right there. Now you can pass data as the variable.
f(x)=2x+1
f(3)=2*3+1
f(3)=6+1
f(3)=7
You can pass any number through the function to find the result. It is the same idea with programming functions. Here is an example of a SCAR function that would work like the math function above.
function stupidMathFunction(x:integer):integer; // declare function name, input variables, and result datatype
begin
result:=2*x+1;
end;
If you ran "stupidMathFunction(3)" it would return 7, just like the above math function. Functions can return any datatype you set it to. Since I wanted to return the result of a math expression, I set the result datatype to integer. In SCAR, there are functions and procedures. Both can have input variables, but Functions will return something, while procedures will just perform something. since functions return a variable, they can be used in conditions. In other languages, there may only be 1 type of module, and the user will specify if anything is returned. Something like:
function newFunction() { // this one assigns newVar then will return it
var newVar = 0;
return newVar;
}
function newFunction2() { // this one just assigns newVar, nothing returned
var newVar = 0;
}
One of the best parts of programming any language is creating your own methods that will manipulate data how you need it to. Then you can just pass a variable through your custom function, instead of having to run all the commands on each variable seperately. These leads me to the next part of the tutorial…3. EFFICIENCY
3.1 Common Problems
Keeping code efficient is a big part of any language. Too much uneccessary code can yield bad results. For one, when code gets excessive and messy, it can get hard to edit and cause confusion in the programmer. This can lead to Ghosts. Simply put, ghosts are pieces of code that are formed from half removed pieces of code, along with lines that may not be needed but havent been removed. Ghosts can run unnecessary commands that can take up memory, or even cause wierd results or errors. Along with this comes the term Spaghetti Code. I always thought that was a funny name for it, but spaghetti code is exactly what it sounds like: when your code is all tangled up in itself like spaghetti. This can cause insufficient use of memory, errors, or even memory leaks. Using SCAR, you wont have to worry to much about spaghetti code, since SCAR is single threaded, and since its compiled all errors will be caught before running.
3.2 Planning
Making an efficient script is all about planning. You need to think about what you are going to create. Think about all the methods you want to use to do what you want. Always plan for upgradeability later. You dont want to finish something, and then a week later have to rewrite the whole idea because you need to add something important. The best idea, if you really want to plan out your code, is to use a flowchart. A flowchart is a drawing depicting how a program/script will work. I, myself, do not usually draw out a flowchart, but I create one in my head days before I start writing any code. to learn more about flowcharts visit:
http://en.wikipedia.org/wiki/Flowchart
3.3 Redundancy
Since I am not talking about database languages, we do not need to worry about Redundancy that much, but I'll skim over it in terms of how to reduce it in scripts. Redundancy is unnecessary repetitiveness. The best way to reduce redundancy in a script, is to do what I mentioned earlier. Create a custom function to run certain commands, so you can call the single function, instead of calling all the commands.
the more you know.