Where Lua is Used
Apache HTTP Server
MysqlWorkbench
Redis
VLC Media Player
Wireshark
Lots and lots of games!
Types
8 basic types
nil
boolean
number
string
[[ this is a
multi line data]]
userdata
function
thread
table
signle Assignment
x = 1
multiple assignment
x,y = 10,20
NOTE
variable print use:
print(varname)
exchange two variables example
x = 1
y = 2
x,y = y,x
Expressions
Expressions = value
Type of expresions
Numeric constants
String literal
Variable
Unary and binary operations
Function calls
Function definitions
Table constructions
Operators:
Arithmetic(算术) (+,-,*,/,^,%)
Relational(<,>,<=,>=,==,~=)
Note:not equal is ~= in lua
Logical (and,not,or)
Other
Concatenation
"Hi" .. "there"
Length
#suckers
name = "aaa"
print(#name) -- show the length of name string variable
If,Then,Else
if boolean expression then
--do something
else
--else if also can be used
--do something
end
Loops
While - while boolean expression do something end
Repeat - repeat something until boolean expression
For (Numeric) - for variable = start,end,step do something end
for i = 1,10 do print(i) end --the step can be omitted,default is 1
For(Generic) - for k,v in iterator do something end
Scope
By default,all variables in Lua are globally scoped
Functon
Functions in Lua are first class citzens,that means they are like any other type
Note:functions should be declared before being used
Variadic functions(变参函数)
function countStringLengths(...)
--do stuff
a,b,c = ...
end
All functions declared are actually stored in variables
When we write:
function askQuestion(q)
--do stuff
end
it really means:
askQuestion = function(q)
--do stuff
end
Closures
Even though Function A is out of scope,Function B can still access Function as local variable
Tables
A table is an extremely flexible data structure
Table elements can be accessed by using the '.' syntax,for example:
grade.teacher
also can be accessed by using the '[]' syntax,for example:
grade['Teacher']
The key of a table can be not quoted if key is a string, for example:
grade[namel = 'jack']
Just about any data structure can be created with a table
Arrays
in lua,array index starts from 1,not from 0 like many other programming lanugages do
Object-Oriented Code Works in Lua
In Lua,we can simulate classes using tables
Metatables allow us to redefine some table behavior
Metamethods
__index
__newindex
Operators
__add
__sub
__mul
__concat
...
__call
__tostring
Use metamethods,we can make tables very flexable
Classes
There are no direct-support in Lua,but the ":" gives us a little help
Inheritance is pretty easy using our 'class' system
Modules
We can create reusable modules in Lua
git@github.com:yaowenqiang/lua-demo.git
转载于:https://my.oschina.net/8pBwdEmxK2hL/blog/232797