LUA:For C Programmers

From GMod Wiki

Jump to: navigation, search
Lua: Lua for C Programmers
Page white text.png Description:A crash course in Lua for people who already know C, C++, or C#
link=User:CloneDeath Original Author:CloneDeath
Group.png Contributors:The community
Calendar.png Created:July 8, 2010

About

This is a WIP. Lua for Python Programmers was used for a template..

For the remainder of the article, when I refer to "C", I mean C, C++, and C#.

The Basics

I'd recommend first reading this page, as it explains how to make and run Hello World in Lua. Got that done? Good.

Lua code will look crazy and awkward to a C programmer, but all the concepts are the same, and you should be able to pick it up easily.

Variables

Unlike C, Lua variables don't have an explicit data type.

Here is some code in each language to declare different variables.
C

int myInt = 0;
char myChar = '0';
char* myString = "Hello World\0";
float myFloat = 0.0;
int myArray[10];
	...

Lua

myInt = 0
myChar = "0"
myString = "Hello World"
myFloat = 0.0
myArray = {}
	...
end

There are a few differences, but you should be able to draw parallels. There is line terminator (aka ";"), just do a newline character.

Types of variables are dynamic. The best way to show this is via example.

C

//myInt is an int = 0
int myInt = 0;
//myInt is still an int, and changes the 4.3 to 4
myInt = 4.3;
//ERROR! NO! Can't do it!
myInt = "woosh";
	...

Lua

//myInt is an int = 0
myInt = 0
//myInt is now a float, and it is now equal to 4.3
myInt = 4.3
//myInt is now a string, and it is now equal to "woosh"
myInt = "woosh"
	...

Boolean Values

In C there is no such thing as a Boolean (There is in C++/C#, so if you know C++/C# skip to below), but you probably have done C

#define TRUE 1 /* anything but 0 really */
#define FALSE 0
	...

In that case, TRUE in C is basically the same as TRUE in lua. One key fact I want to point out is the evaluation of conditionals. In C, everything evaluates to true except 0 (which is false). This is not true in Lua. Lua treats everything as true except for the values nil and false. Meaning, in Lua, 0 evaluates to true.

Also key are the various boolean operators. The Garry's Mod implementation of Lua uses &&, ||, and ! for and, or, and not respectively. They all behave pretty much the same as C does.

Control Structure

Shown are various constructs in C and their equivalent lua code


C

int fn(int param1,const char* param2,double param3){
    /* code */
    return 0;
}

Lua

function fn(param1,param2,param3)
    /* code */
    return 0
end


C

if (condition){
    /* code */
}

Lua

if condition then
    /* code */
end


C

char str[80];
strcpy (str,"these ");
strcat (str,"strings ");
strcat (str,"are ");
strcat (str,"concatenated.\n");
printf(str);
 

Lua

str = "these " .. "strings " .. "are " .. "concatenated."
Msg(str).
 
//or
 
str = "strings"
str2 = Format("these %s are concatenated.", str)
Msg(str2)
 
//OR: (no real C equivalent for this one, but you should be able to figure it out.)
str = "strings"
Msg("these " .. str .. " are concatenated.")

Output: these strings are concatenated.


C

printf("Beginning %d End",10)

Lua

Msg("Beginning "..10.." End")
//or
Msg(Format("Beginning  %d End", 10))

Output: Beginning 10 End


C

for (int i = 0; i < 10; i++){
	...
}

Lua

for i=0,10 do
	...
end

In lua, it is basically saying "for each value between 0 and 10 (inclusive), do this:"

Tables

An avid C programmer will be no doubt familiar with the power of arrays, but their brain will explode when they learn about lists and dictionaries. Lua uses "arrays", but they are called Tables. Essentially, a table is an array, but you can use anything to index it, not just integers. The syntax to define, set values, and retrieve values similar.

 
myTable={}
 
myTable[240]=25 
myTable[231]="potato"
myTable[92]=48 
myTable[119]=52
myTable["george"]=1 
myTable["alex"]=3 
myTable["orange"]=17
myTable["cake"]="lie"
 
myTable[240] // Returns 25
myTable["george"] // Returns 1
myTable[231] // Returns "potato"
myTable["nope"] // Returns nil, because this key has not been assigned a value
 

It seems weird, but once you think about it, you should be able to understand it.

There's also a beautifully "for each" loop in lua:

The For-In Loop

Lua

for key, value in pairs(myTable) do
	...
end

key will be the index (it could be a number, string, float, whatever you put between the square brackets "[]" to set the value. value will be the value (it could be a number, string, float, whatever you put after the equals sign "=" to set the value.)

For fun, try running this Lua Script, it may clear some things up: Lua

myPlayer={}
 
myPlayer["Health"]=100
myPlayer["Favorite Color"]="Green"
myPlayer[0]="Gun"
myPlayer[1]=100
myPlayer[30]=woosh
myPlayer[12]=111.2
 
Msg("Print out of myPlayer:\n"
for key, value in pairs(myPlayer) do
    //--[key] = [value]
    Msg("--"..key.." = "..value)
end

That should output each key/value pair in myPlayer. Useful for debugging ;)

Personal tools
Namespaces
Variants
Actions
Navigation
Lua Scripting
Functions
Hooks
Toolbox