Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

One of Lua's study notes (first-class topics)


May 12, 2021 Lua


Table of contents


Objective

This article is aimed at experienced C/C?programmers who want to learn about Lua or quickly grasp Lua's key concepts and patterns for development. T herefore, this article is not intended to teach the reader the syntax of conditional statements or the way functions are defined and so on, as well as some basic concepts of programming languages such as variables, functions, etc. T his article is intended only to tell the reader what is significantly different from C/C+ and how they actually bring about a different way of thinking than C/C? Don't look down on them, they're about to upend your traditional C/C worldview!

This article is divided into three parts: first order, advanced level and high order, each part has several chapters. R eaders should read step by step from start to finish, but chapters marked with the """ R eaders can do most of the tasks of Lua development by completing the first two parts. The higher order section is available as an option.

First-order topics

1. Eight basic types: The following table

The basic type

Describe

Note

Value (number)

The interior is represented by double

String (string)

Always ends with zero, but can contain any character, including zero, so it is not equivalent to a C string, but rather its superset

Boolean

There are only two values, true or false.

Functions

One of the key concepts of Lua. A function or function pointer that is not simply equivalent to C.

Table

Heterogeneous Hash table. One of the key concepts of Lua.

userdata

The C data structure defined by the user (non-scripted user). Script users can only use it, not define it.

Thread

Lua collaboration threads (coroutine) are not the same preemptive threads as the general operating system.

nil

Represents nothing and can be compared to C's NULL, but it is not an empty pointer.

2. Function

2.1 instance code

    function foo(a,b,c,...)  
        local sum = a+b
        return sum,c  --函数可以返回多个值
    end

    r1,r2 = foo(1,"123","hello")--平行赋值
    print(r1,r2);

Output:

124 hello

2.2 The basic method of use of functions

  • Function definition:

Define the function with the keyword fusion, ending with the keyword end

  • Local variables:

Defined with the keyword local. If not defined in local, even variables defined inside functions are global!

  • The function can return multiple values:

return a, b, c, ...

  • Parallel assignment:

a, b = c, d

  • Global variables:

The previous code defines three global variables: foo, r1, and r2

3. Table

3.1 Implementation code

    local a = {}
    local b = {x = 1,["hello,"] = "world!"}
    a["astring"] = "ni,hao!"
    a[1] = 100
    a["a table"] = b

    for k,v in  pairs(a) do
        print(k,"=>",v);
    end

Output:

1=>100

astring=>ni,hao!

a table=>table: 0xfd59570

3.2 How the table is used

  • How tables are defined

a = {}, b = {...}

  • Access to the members of the table

By "." Or the """"

Note: The expression .b is equivalent to a .

  • The key and value of the table item

    Any type of variable, except nil, can be used as a key for a table item. F rom simple values and strings to complex functions, tables, and more; S imilarly, any type of variable, except nil, can be used as a value for a table item. A ssigning nil to the value of a table item means deleting the item from the table, such as the item with the key "b" in table a, for example, by making a.b. I f you access a table item that does not exist, and its value is also nil, for example, if there is a c .b, but there is no item in table a with a key of "b", then c is equal to nil.

4. A simple way to implement an object

4.1 Implementation code

    function create(name,id)
        local obj = {name = name,id = id}

        function obj:SetName(name)
            self.name = name 
        end

        function obj:GetName()
            return self.name
        end

        function obj:SetId(id)
            self.id = id
        end

        function obj:GetId()
            return self.id
        end
        return obj
    end

    local myCreate = create("sam",001)

    for k,v in pairs(myCreate) do
        print(k,"=>",v)
    end

    print("myCreate's name:",myCreate:GetName(),"myCreate's id:",myCreate.GetId(myCreate))

    myCreate:SetId(100)
    myCreate:SetName("Hello Kity")

    print("myCreate's name:",myCreate:GetName(),"myCreate's id:",myCreate:GetId())

SetName=>function: 0x85efc50

GetId=>function: 0x85efc10

id=>1

SetId=>function: 0x85efd00

GetName=>function: 0x85efce0

name=>sam

myCreate's name:sammyCreate's id:1

myCreate's name:Hello KitymyCreate's id:100

4.2 Object implementation description

  • Object factory mode

Such as the creative function of the previous code

  • Use tables to represent objects

Putting the object's data and methods in one table, while not hiding private members, is perfectly acceptable for simple scripts.

  • The definition of the member method

    function obj:method(a1, a2, ...) ... e nd is equivalent to fusion obj.method (self, a1, a2, ...) ... e nd is equivalent to obj.method s function (self, a1, a2, ...) ... end

  • The call to the member method

obj:method (a1, a2, ...) equivalent to obj.method (obj, a1, a2, ...)

5. Simple inheritance

5.1 Implementing code

    local function CreateRobot(name,id)
        local obj = {name = name,id = id}

        function obj:SetName(name)
            self.name = name
        end

        function obj:GetName()
            return self.name
        end

        function obj:SetId(id)
            self.id = id
        end

        function obj:GetId()
            return self.id
        end
        return obj
    end

    local function createFootballRobot(name ,id ,position)
        local obj = CreateRobot(name ,id)
        obj.position = "right back"

        function obj:SetPosition(p)
            self.position = p
        end

        function obj:GetPosition() 
            return self.position
        end

        return obj
    end

    local mycreateFootballRobot = createFootballRobot("Tom",1000,"广州")

    print("mycreateFootballRobot's name:",mycreateFootballRobot:GetName(),"myCreate's id:",mycreateFootballRobot:GetId(),mycreateFootballRobot:GetPosition())

    mycreateFootballRobot:SetName("麦迪")
    mycreateFootballRobot:SetId(2000)
    mycreateFootballRobot:SetPosition("北京")
    print("mycreateFootballRobot's name:",mycreateFootballRobot:GetName(),"myCreate's id:",mycreateFootballRobot:GetId(),mycreateFootballRobot:GetPosition())

Output:

mycreateFootballRobot's name:TommyCreate's id:1000right back

mycreateFootballRobot's name: MaddiemyCreate's id: 2000 Beijing

5.2 Simple inheritance of advantages and disadvantages

Pros: Simple and intuitive

Cons: Traditional, not dynamic enough

Reference " Luke's Quick Start for C/ C ? Programmers"