Lua profile

As a scripting language (interpreted language), Lua claims to be the highest performance scripting language, and is widely used in many performance-demanding areas, such as Nginx, game scripting, OpenResty, and so on. In my project Agent, LUa script is used to realize the task processing logic. When the task executor receives a task, it selects the corresponding Lua script to execute the task, decouples the task from the executor, and supports hot update.

Introduction to the Lua

The installation

Lua installation is very simple. If you are running Linux, replace make Macosx test with make Linux test

Curl the -r -o http://www.lua.org/ftp/lua-5.3.5.tar.gz tar ZXF lua - 5.3.5. Tar. GzcdLua - 5.3.5 make Linuxtest
Copy the code

hello world

Start with the simplest hello World

$lua Lua 5.3.5 Copyright (C) 1994-2018 Lua.org, puc-rio >print("hello world")
hello world
Copy the code

type

nil

Nil is a type, understood as NULL, whose main function is to distinguish it from any other value. Assigning nil to a global variable is equivalent to deleting it.

boolean

Boolean types have two optional values: false and true. Lua treats false and nil as false, other values as true and, unlike other scripting languages, numeric zeros and empty strings as true.

number

The number type is used to represent real numbers. Lua has no integer type, only double.

string

Lua is fully 8-bit encoded, and strings are immutable values.

> str="hello world"
> print(str)
hello world
Copy the code

Lua can also define a string with a matching pair of double parentheses.

> str=[[
>> print("hello world")
>> hello world
>> ]]
> print(str)
print("hello world")
hello world
Copy the code

table

The table type implements associative arrays. It is an array with a special index that can be indexed by integers, strings, or other types of values. Based on table, it can be used to represent ordinary arrays, symbol tables, collections, records, queues, and other data structures. Lua also uses tables to represent modules, packages, and objects.

array = {}
array[1]=1
array["2"]=2
array[3]="3"
Copy the code

function

In Lua, functions are class-1 values, which can be stored in variables, passed as arguments to other functions, and returned as values from other functions.

local add = function(a,b)
    return a+b
end

function add1(a,b)
    return a+b
end

print(add (1, 2))Copy the code

expression

Relational operator

Like other languages, Lua supports <,>,<=,>=,==,~=.

Logical operator

Logical operations are AND, OR, and not. For the and operator, we return the first operand if the first operand is false, otherwise we return the second. The operator or returns the first operand if the first operand is true.

String conjunction

You can use the operator.. (Two points)

print("hello"."world")
Copy the code

Control structure

if then else

a = 2
if a > 0 then
    print("a is positive")
end
Copy the code

if then elseif then end

a = -1
if a > 0 then
    print("a is positive")
elseif a <0 then
    print("a is negative")
else
    error("a is zero")
end
Copy the code

while

local i=1
local sum=0
while i < 10 do
    sum = sum +i
    i = i+1
end
print(sum)
Copy the code

for

The digital model for

The syntax is as follows: var changes from exp1 to exp2. Each change takes exp3 as the step. If this parameter is not specified, the default step is 1. The # symbol is often used to specify the length of an array.

for var=exp1,exp2,exp3 do
    <execute>
end
Copy the code

Let’s take a simple example

local i=1
local sum=0
forI = 1,10,1do
    sum = sum +i
    i = i+1
end
print(sum)
Copy the code

Generic for

Lua’s base library provides ipairs and Pairs, both of which can be used to traverse collections. The difference between the two is

  • Ipairs simply traverses the values, traversing the index in ascending order, stopping traversal when the index breaks. It exits on nil, and it can only iterate through the first non-integer key that appears in the set.
  • Pairs can iterate over all keys in a collection.
for i,v in ipairs(array) do
    print(v)
end

for i,v in pairs(array) do
    print(v)
end
Copy the code

Metatable and metamethod

In Lua, each value has a predefined set of operations, and the metatartable allows you to modify the behavior of a value to perform a specified operation in the face of a non-predefined operation. Given that elements A and B are of type TABLE, the metatartable defines how to evaluate expressions A +b.

The following is a simple example to implement the addition of two tables

local string = require("string")
localFormat = string.format // Defines two fractions, fraction1 1/3 and fraction2 2/3local fraction1 = {denominator=3,numerator=1}
localFraction2 ={denominator=3,numerator=2} // define an operator fraction_operator={} // define an operator overload of +functionfraction_operator.__add(f1,f2) res = {} res.denominator = f1.denominator * f2.denominator res.numerator = f1.numerator *  f2.denominator + f2.numerator * f1.denominatorreturnSetmetatable setmetatable(fraction1,fraction_operator) setmetatable(fraction2,fraction_operator)print(getmetatable(fraction1))
print(getmetatable(fraction2))

local fraction3 = fraction1 + fraction2
print(format("num:%d,den:%d",fraction3.numerator,fraction3.denominator))
Copy the code

Lua internal convention for MetaMethod

__add(a, b) corresponds to a + b __sub(a, b) corresponds to a - b __mul(a, b) corresponds to a * b __div(a, b) corresponds to a/b __mod(a, b) B) a % b __pow(a, b) a ^ b __unm(a-a__concat(a, b) corresponds to the expression a.. B __len(a) corresponds to the expression#a__eq(a, b) corresponds to the expression a == b __lt(a, b) corresponds to the expression a < b __le(a, b) corresponds to the expression a <= b __index(a, b) corresponds to the expression a.b __newindex(a, b, b) B = c __call(a,...) Corresponding expression a(...)Copy the code

reference

Coolshell. Cn/articles / 10…

Lua programming second edition