LUA:For Python Programmers

From GMod Wiki

Revision as of 15:31, 10 February 2011 by garry :D (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
Lua: Lua for Python Programmers
Page white text.png Description:A crash course in Lua for people who already know Python
link=User:Darkspork Original Author:Darkspork
Group.png Contributors:The community
Calendar.png Created:Dec 7, 2009

About

This is a WIP

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 very familiar to a Python programmer. As in Python, Lua variables don't have an explicit data type. Lua also has a very familiar data structure and looping construct. I'm getting ahead of myself, though.

Boolean Values

One key difference between Python and Lua is the treatment of boolean variables. In Python, just about anything that resembles "zero" or "empty" evaluates to false. This is not true in Lua. Lua treats everything as true except for the values nil and false.

Also key are the various boolean operators. The Garry's Mod implementation of Lua uses &&, ||, and ! for and, or, and not respectively. The &&/|| operators behave exactly like Python's and/or operators - they return one of the two values, rather than simply true or false. Note that the regular lua syntax is completely supported as well.

Control Structure

Shown are various constructs in Python and their equivalent lua code


Python

def fn(param1,param2,param3...):
	...

Lua

function fn(param1,param2,param3...)
	...
end


Python

if condition:
	...

Lua

if condition then
	...
end


Python

"Beginning %s End"%(MiddleString,)

Lua

"Beginning "..MiddleString.." End"
//or
Format("Beginning  %s End", MiddleString)


Python

"Beginning %d End"%(MiddleNumber,)

Lua

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


Python

for (i in range(low,high)):
	...

Lua

for i=low,high do
	...
end

Tables

An avid Python programmer will be no doubt familiar with the power of lists and dictionaries. Lua brings both of these together in the Table. Essentially, a table is a dictionary. The syntax to define, set values, and retrieve values is identical.

 
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"
 

There's also a beautifully familiar loop:

The For-In Loop

Python

for (key, value) in dict:
	...

Lua

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

Classes

Personal tools
Namespaces
Variants
Actions
Navigation
Lua Scripting
Functions
Hooks
Toolbox