Redis Lua script school tutorial (under)

In the upper half of the middle school tutorial we introduced Redis Lua-related commands, not read or forget the students can walk to the ticket directly Redis Lua script school tutorial (on) . Today we simply learn the syntax of Lua.

Before introducing grammar Lua, Lua first to introduce life experience. Lua is a PUC-Rio team designed, developed and maintained by simply called. Lua is in Portuguese meaning the moon, so it is not short, but a noun. I can only write Lua, but can not be written LUA or whatever. Next we officially Getting Lua.

variable

Variable name can be a string of letters, numbers and underscores, but can not start with a number. Also important to note is the need to try to avoid using the underscore plus one or more variable names capital letters, because it is a reserved word Lua, in addition to this format, there are some general format of reserved words:

and break do else elseif
end false for function goto
if in local nil not
or repeat return then true
until while

Lua is case-sensitive, and is a reserved word, but And and AND are not.

Global Variables

We mentioned earlier is not supported by Redis Lua global variables, but Lua itself is to support global variables.

Global variables need not be declared, a direct uninitialized variables when its value is nil.

> b --> nil
> b = 10
> b --> 10
复制代码

If the display will be nil assigned to a global variable, Lua think we no longer use this variable.

Local variables

Lua variables default global variables, local variables need to be explicitly declared. Local variable names to avoid unnecessary confusion to the global environment, but also to avoid naming conflicts in two parts of the code. In addition, access to the local variables than global variables faster access speed.

Local variable range is limited, it is only available at block declared. (May be a control block structure or function of the body or the entire document)

x = 10
local i = 1 -- local to the chunk
while i <= x do
local x = i * 2 -- local to the while body
print(x) --> 2, 4, 6, 8, ...
i = i + 1
end
if i > 20 then
local x -- local to the "then" body
x = 20
print(x + 2) -- (would print 22 if test succeeded)
else
print(x) --> 10 (the global one)
end
print(x) --> 10 (the global one)
复制代码

In interactive mode, each block of code is input, when you enter local i = 1, it defines a local variable i, and when you use the next row i, found that it became a global variable. Therefore, the above chestnuts can not be used. To solve this problem, we need to explicitly used in the program do-end range marker code block.

local x1, x2
do
  local a2 = 2*a
  local d = (b^2 - 4*a*c)^(1/2)
  x1 = (-b + d)/a2
  x2 = (-b - d)/a2
end                      -- scope of 'a2' and 'd' ends here
print(x1, x2)            -- 'x1' and 'x2' still in scope
复制代码

This way mark block range is a good habit, but also better than using a local variable programming using global variables, so many people called for Lua default should define local variables, but this will be a problem. The best solution is to not default, must declare all variables before using.

Lua has a common idiom:

local foo = foo
复制代码

Here foo defines a local variable, global variable and the value assigned to the local variable foo. This idiom is mainly used to enhance the access speed of the variable foo, or temporary storage of variables, prevent other function to change the value of this variable.

Note

Single-line comments

The single-line comments Lua double dash "-" indicates that the contents of the double line of annotation content.

Multi-line comments

A manifestation of the multi-line comment is based on double-dash with double left bracket and ending with the double right bracket. E.g:

--[[A multi-line
long comment
]]
复制代码

But usually we use another way: to double emphasis added dual left bracket and ending with the double dash with double right bracket, such an approach look more beautiful, but also more convenient solution comments:

--[[
print(10) -- no action (commented out)
--]]
复制代码

Solution Notes

---[[
print(10) --> 10
--]]
复制代码

Here we explain a little of the principles of such an approach, when the comment, the double line in a group of annotation content, and therefore does not work, for reasons of symmetry only, and the general effect of the same multi-line comments. Note solution while, before the first set of a double line added a horizontal line, can not be considered a multi-line comment, the comment only as a single line, thus, the first line is commented out, after a set time-bis a horizontal line will work, double right bracket commented later.

type of data

Lua is a dynamically typed language, which has eight basic types: nil, Boolean, number, string, userdata, function, thread and table. specify the type of function may return type value:

> type(nil) --> nil
> type(true) --> boolean
> type(10.4 * 3) --> number
> type("Hello world") --> string
> type(io.stdin) --> userdata
> type(print) --> function
> type(type) --> function
> type({}) --> table
> type(type(X)) --> string
复制代码
Nil

Nil is only one type of value is nil, it did not show a value.

Boolean

There are two types Boolean values, @ false {} and @true {}. But Boolean type does not include all of the conditions values: in the conditional, Lua will be judged false and nil as false, others are determined to be true.

Vo: Lua 0 and an empty string but also the determination is true, this is not good sense of design

and, or and not logical operators are Lua.

and the operation method is the first operand judgment is not false, if not, the result is the second operand.

or the computing method is determined first operand is not true, and if not, the result is the second operand.

> 4 and 5 --> 5
> nil and 13 --> nil
> false and 13 --> false
> 0 or 5 --> 0
> false or "hi" --> "hi"
> nil or false --> false
复制代码
Table

Table Lua is in the main (and only) the performance of structured data types. It can be used to represent a wide variety of data types, such as an array, a set of records.

Key table may be different for each type of index defined for the table element, its default value is nil. And most other languages is a different index tables in Lua is 1-based .

Table available in two formats: record-style and list-style

record-style can be directly used. "" Access, list-style can be accessed by a suffix. We can define together the definition.

polyline = {color="blue",
            thickness=2,
            npoints=4,
            {x=0,   y=0},
            {x=-10, y=0},
            {x=-10, y=1},
            {x=0,   y=1}
}
复制代码

When we visit a possibly empty Table, often need to determine non-empty

if lib and lib.foo then ....
复制代码

With this access deeper structure of representation will be very painful:

zip = company and company.director and
                      company.director.address and
                        company.director.address.zipcode
复制代码

Lua is not the same as C # provide? Such an operation, but we can use the form or {} to handle.

zip = (((company or {}).director or {}).address or {}).zipcode
复制代码

Process Control

Lua provides some basic flow control statements:

  • determining if conditions for
  • while, repeat for convenience and for
  • end may be terminated if, for and while
  • until may terminate repeat
  • break out of the loop for
  • return for the jump function
  • goto will jump to a specified location

function

Lua can receive a function parameter is list, if there are no parameters need to write an empty pair of brackets "()" (nonsense). If only one parameter, the brackets can write from time to write. Lua also provides a special function access methods, are interested can refer to https://www.lua.org/pil/16.html

o:foo(x)
复制代码

Lua program can either use the functions defined in Lua, and defined functions can also be used in the C language.

Lua function has a very convenient feature: a plurality of results may be returned.

function maximum (a)
  local mi = 1
  local m = a[mi]
  for i = 1, #a do
    if a[i] > m then
      mi = i; m = a[i]
end end
  return m, mi
end

print(maximum({8,10,23,12,5}))     --> 23   3
复制代码

Lua can automatically adjust the number of results returned when the function is called as the statement will discard all return values; when the expression as a function call, leaving only the first return value; if you want to get the full return value, function calls need to be expressed The last type.

Lua function also supports variable parameters:

function add (...)
  local s = 0
  for _, v in ipairs{...} do
		s=s+ v 
  end
return s 
end

print(add(3, 4, 10, 25, 12))   --> 54
复制代码

to sum up

To briefly summarize, this article we introduced the basic syntax of Lua, including how to define variables (including global and local variables), some of the features eight basic data types, flow control statements and functions in Lua. I believe after reading this article, you can write some simple Lua script.

Lua for interested students can go on their own Lua's official website for further studies.

Reproduced in: https: //juejin.im/post/5d0b8db96fb9a07ee0631dc1

Guess you like

Origin blog.csdn.net/weixin_33857679/article/details/93176622