10-Minute Interactive starter LUA tutorial

Source: Internet
Author: User
Tags anonymous constant numeric lua require
Lua is a language.

A small scripting language designed to embed applications, providing flexible extension and customization capabilities for applications. LUA is written in standard C and can be compiled and run on almost all operating systems and platforms. features Lua scripts can be easily called by C/C + + code, or they can be invoked in reverse. LUA is written in standard C, and the code is simple and beautiful, and can be compiled and run on almost all operating systems and platforms. Provides comprehensive functionality with minimal volume and simple syntax. [A full LUA interpreter but 200k, Lua is the fastest in all of the current scripting engines] implementing a clean interface to the host language becomes a very easy language to embed in other languages. features support object-oriented programming lightweight extensible functional programming automatic memory management common Type table –table, can implement array, hash table, collection, object support multi-threading support interactive programming- use game development, more for game scripting development
http://love2d.org/Embedded Development Web application script extension and database plug-in security system installation

http://www.runoob.com/lua/lua-environment.html Learning Resources http://lua-users.org/files/wiki_insecure/users/ Thomasl/luarefv51.pdf Quick Reference Manual http://www.runoob.com/lua/lua-tutorial.html Beginner Tutorial https://wizardforcel.gitbooks.io/ W3school-lua/content/w3school Tutorial Interactive

Interactive programming
Lua provides an interactive programming model. We can enter the program on the command line and see the effect immediately.
The LUA interactive programming model can be enabled by command lua-i or LUA:

$ lua 
$ lua 5.3.0  Copyright (C) 1994-2015 lua.org, Puc-rio

On the command line, enter the following
> Print ("Hello World". ")
Hello World. Interactive Learning Lua introductory experience 1. How to run LUA files:

$ LUA Helloworld.lua
refer to the introductory case yourself and try it out in the interactive terminal on the right. Beginner's Tutorial

Basic data types

-------------------------------------------------------Basic Grammar---------------------------------------------------- ------Comment-This is a single-line comment--[[This is a multiline comment--"]--delete variable n = ten print (n) n = bil--delete variable print (n)----------------------- ---------------------------------Data Type----------------------------------------------------------------
Lua is a dynamic type language, and a variable does not require a type definition, only a variable must be assigned a value. Print ("Data type: nil") print ("\ n") print ("Data type: boolean") print (type (true)) print (type (false)) print ("\ n") Print ("Data type: Number")--Lua defaults to only one number type-double (double) type print (2.3) print ("\ n") print ("Data type: String")--word
string is represented by a pair of double or single quotation marks. Print ("Hello World in Lua")--you can also use 2 square brackets "[[]]" to represent a "piece" of string str = [[Hello in the world!]] Print (str)-Calculate string length pri NT ("The length of STR is").
#str)--use # to calculate the length of print ("\ n") print ("Data type: Table")--important--an array different from other languages uses 0 as the initial index of the array, and the default initial index of the table in Lua typically starts at 1. tab = {key1 = ' value1 ', key2= ' value2 '} for k,v ' Pairs (tab) do print (K. "-"..
V)--connector: EnD print ("\ n") Tabt = {}--empty table tabt["Key3"] = "value3" Key4 = "Key4" tabt[key4] = "Vlaue4" for k,v in pairs (TABT) do Print (k: "=": V) End--index--use square brackets [] for the index of the table. Lua also provides the.
Operation. Print ("index": Tabt[key4]) Print ("Index": Tabt.key3) print ("\ n") print ("Data type: function") print (type (print)) function demo () return "Hello" End Print (Demo () )--Anonymous function anonymous (TAB,FN) for k,v in Pairs (tab) do print (FN (k,v)) end End Anonymous (tabt,fun Ction (k,v) return K: " ==".. V end)--array print ("\ n") arr = {1,4, "h"} for i = "Array": I.. "= =": Arr[i]) End print ("\ n Multidimensional array") ARRM = {} Arrm[1] = {Arrm[2}] = {4,5,6} for i=-do-j = 1,3 do print ("Multidimensional array": ARRM[I][J])--notice end end--------------------------------------------------------Lua Variable--------------------------------------------------------------print ("\ n") print ("Lua variable") There are three types of--[[LUA variables: global variables,
Local variables, fields in the table.
The variables in Lua are all global variables, even if the statement block or function is declared as a local variable with the local display. Scope of local variablesTo the end of the statement block from the start of the declaration position.


The default value for a variable is nil. Local variables should be used as much as possible, with two benefits: 1.
Avoid naming conflicts.

2. Accessing local variables is faster than global variables. --]] A = 3 local b = 1 function area () b. Local a = 3 local c = end print ("A is") A)--12 print ("B is"). b)--1 Notice:here B is 1 print ("C is").
Type (c))--nil--Multiple variables are assigned at the same time-note: If you want to assign values to multiple variables, you must assign values to each variable in turn. A, B = "Hello", "World" print (A. b)--------------------------------------------------------Lua
    Loop--------------------------------------------------------------print ("\ n") print ("While loop") I = ten while (i > 0) do 
i = i-1 print (i) end print ("\ n") while (I < 7) do i = i + 1 print (i) end print ("\ n") print ("For Loop")
In the--[[LUA programming language, there are two broad classes of for statements: numeric for loop generic for loop--------------Lua programming language numeric for Loop syntax format: For three expressions are evaluated once before the loop starts, and are no longer evaluated.
For VAR=EXP1,EXP2,EXP3 do < actuator > end var changes from EXP1 to EXP2, each change increments var by exp3 as step, and executes once "executor".
EXP3 is optional, and defaults to 1 if not specified. --]] for i=0,10 does print (i) End Function f (x) return x*5 end for I=1,f (5), 2 do print (i) End-- generic for loop print ("generic for Loop")--a generic for loop iterates through all values, similar to a foreach statement in Java, through an iterator function. -I is the array index value, and V is the array element value of the corresponding index.
Ipairs is an iterator function that is provided by LUA to iterate over algebraic groups. arr = {1,23,4,55,1,3234,4} for i,v in Ipairs (arr) does print ("Generic for Loop:"). I.. ' '.. V) End print ("\ n") print ("Repeat until") i = repeat print (i) i = i-1 until (i < 0)------------------- -------------------------------------Lua Process Control--------------------------------------------------------print ("\ n"
    if (true) then--note that this is then print ("If Contro") End a = +--if else if (a >100) then print (a+100) Else Print (a) end--If elseif else if (a<200) then print ("a<200") ElseIf (a <100) then print ("a<100") el SE Print (a) End--------------------------------------------------------Lua
function-----------------------------------------------------------------------Lua function can return multiple result values--return, a, variable parameter--[[ The LUA function can accept a variable number of arguments, similar to the C language in the Function argument list using three points (...).
Indicates that the function has variable parameters.
Lua places the parameters of the function in a table called ARG, #arg represents the number of arguments passed in.
  --]] function cot (...)  Return "Number of parameters is". #arg End Print (cot (1,2,3,4,5))--------------------------------------------------------Lua operator-----------------------------------------------------------------------http://www.runoob.com/lua/ lua-miscellaneous-operator.html A = b = ten c = a + B print ("Line 1-c value is", c) C =-A-a print ("line 2-c value is",  c) C = A * b print ("Line 3-c value is", c) c = A/b print ("Line 4-c value is", c) C = a% b print ("Line 5-c value is", C) c = a^2 Print ("line 6-c value is", c) c =-a print ("line 7-c value is", c) A = true b = False if (A or B) then print (A O R b) End--------------------------------------------------------Lua string---------------------------------------------------------------------str = "Hello in world!" Lua loved! "Print (String.upper (str)) print (String.Lower (str)) print (String.reverse (str))-------------------------- ------------------------------Lua table-----------------------------------------------------------------------[ [Table is a number of LuaThe structure is used to help us create different data types, such as numbers, dictionaries, and so on.
Lua table uses an associative array, and you can count the group's index with any type of value, but this value cannot be nil.
Lua table is a non-fixed size that you can scale to fit your needs. LUA also solves modules (module), Packages, and objects (object) through table.

For example, String.Format indicates that the table string is indexed using "format". --]] print ("\ n") Print ("Table connection") fruits = {1,2,3,4} print ("After Connection", Table.concat (Fruits, '-')) print ("\ n") print ("\ nthe" table ins ert and remove) table.insert (fruits, "hh") print (Fruits[5]) table.remove (fruits)--Returns the element of the table array part at the POS location. The subsequent elements are moved forward. The POS parameter is optional and defaults to the table length, which is the deletion of print from the last element ("Table sort") table.sort (fruits) for k,v in pairs (fruits) do print (K..) --".. V) End--------------------------------------------------------Lua Collaborative program-----------------------------------------------------------------------Notice:: Collaborative Program on the online IDE,


Using Coroutine.resume () cannot print out specific values, so it is recommended to practice locally. Print ("\ n------------coordinator-----------------\ n")--[[Lua Collaboration Program (Coroutine) is similar to threading: having a separate stack, independent local variables, independent instruction pointers,
It also shares global variables and most other things with other collaborative programs.
Synergy is a very powerful feature, but it is also very complex to use.
The main difference between a thread and a co-worker is that a program with multiple threads can run several threads at the same time, while a co-program needs to work cooperatively. At any given moment onlyA synergistic program is running, and the running co-program is suspended only when it is explicitly requested to be suspended.


A co-program is somewhat similar to a synchronized multi-threading, and several threads waiting for the same thread lock are somewhat similar in synergy. Coroutine.create () creates the Coroutine, returns the Coroutine, and the parameter is a function that wakes the function call Coroutine.resume () restarts coroutine when used with the resume,  Using Coroutine.yield () to suspend coroutine with Create, the coroutine is set to a suspended state, which can have a lot of useful effects when used with the resume coroutine.status () View the status of Coroutine note: There are three types of coroutine: dead,suspend,running, when there is such a status please refer to the following program Coroutine.wrap () Create coroutine, return a function, Once you call this function, it goes into coroutine, and the Create function repeats coroutine.running () to return the running Coroutine, a coroutine is a thread, when using running, is to return a corouting thread number--]]--[[Synergy has three states: Suspend state (suspended), run state (running), stop State (dead). When we create the co-program successfully, it is suspended, that is, the co-program is not running at this time. We can check the state of the collaboration using the status function:--]] Co = coroutine.create (function () print ("Hello coroutine!") Print (COROUTINE.S Tatus (CO))--suspended print ("\ n----------\ n") CO = coroutine.create (function (a,b,c) print ("Co", A,b,c) end) print ( Coroutine.resume (Co, 1, 2, 3))--function Coroutine.resume to make the cooperative program from the suspended state to run: Coroutine.resume (CO)--in this case, the collaboration program prints "HI", the task is completed, then enter Termination State: PRint (Coroutine.status (CO))---dead print ("\ n----------\ n")--the real strength of synergy is yield, which suspends the running code CO = coroutine.create ( function () for i=1,10 do print ("Co", I) Coroutine.yield () end end) Coroutine.resume (CO) print (Coro Utine.status (CO)) Coroutine.resume (CO)--------------------------------------------------------Lua Module-----------------------------------------------------------------------[[module] similar to an encapsulation library can put some common code in a file, the API

The form of the interface is called elsewhere, which facilitates the reuse of code and reduces the degree of code coupling.
Lua's module is a table of known elements, such as variables, functions, so creating a module is simple, creating a table, then putting the constants, functions that need to be exported, and finally returning the table. --]] module = {} module.constant = "Define constant" function module.fn1 () print ("Defines a public function.) ") End local function fn2 () print (" Private function ") End return module---Load module--[[LUA provides a function called require to load the module. To load a module, you simply call it.








 Example: Require ("< module name >") or Require "< module name >"--]
minutes Learning Lua_ English version:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.