Introduction to unity3d development (II) — Introduction to Lua


Wuyi Yinxia, whose real name is Guan Jianchang, has a 12-year game career. This tutorial takes unity 3D + vs code + c# + tolua as an example.


If you don’t have a basic programming, I suggest you learn some basic programming first. This article is not a complete rookie tutorial. It is mainly aimed at developers with experience in other languages. If you want to see the rookie tutorial, you are recommended to see the rookie tutorialLua tutorial

First look at the code of a simple class

  1 [email protected] BsnsPack @Base class of business pack
  2 local BsnsPack = {
  3     -- class fields
  4     maxSerialNo = 0,
  5 }
  7 BsnsPack.__index = BsnsPack
  9 --- new()
 10 [email protected] BsnsPack
 11 function
 12     local o = {}
 14     -- member fields
 15     o.serialNo = 0
 16     o.mod = 0
 17     o.cmd = 0
 18     o.payload = nil
 20     -- bind BsnsPack methods
 21     setmetatable(o, BsnsPack)
 22     return o
 23 end
 25 --- set serial No.
 26 [email protected] serialNo number
 27 function BsnsPack:setSerialNo(serialNo)
 28     self.serialNo = serialNo
 29 end
 31 --- get serial No.
 32 [email protected] number
 33 function BsnsPack:getSerialNo()
 34     return self.serialNo
 35 end
 37 --- set mod
 38 [email protected] mod number
 39 function BsnsPack:setMod(mod)
 40     self.mod = mod
 41 end
 43 --- get mod
 44 [email protected] number
 45 function BsnsPack:getMod()
 46     return self.mod
 47 end
 49 --- set cmd
 50 [email protected] cmd number
 51 function BsnsPack:setCmd(cmd)
 52     self.cmd = cmd
 53 end
 55 --- get cmd
 56 [email protected] number
 57 function BsnsPack:getCmd()
 58     return self.cmd
 59 end
 61 --- set payload
 62 [email protected] payload any
 63 function BsnsPack:setPayload(payload)
 64     self.payload = payload
 65 end
 67 --- get payload
 68 [email protected] any
 69 function BsnsPack:getPayload()
 70     return self.payload
 71 end
 73 function BsnsPack.test()
 74     print(BsnsPack.serialNo)
 75 end
 77 --- testPrivate
 78 [email protected] self BsnsPack
 79 local function testPrivate(self)
 80     print(self.serialNo)
 81 end
 83 [email protected] Request BsnsPack @Request is BsnsPack
 84 local Request = BsnsPack
 86 [email protected] Response : BsnsPack @Response class
 87 local Response = {}
 88 setmetatable(Response, BsnsPack) -- bind super methods
 89 Response.__index = Response
 91 --- new()
 92 [email protected] Response
 93 function
 94     local o =
 96     -- member fields
 97     o.code = 0
 99     setmetatable(o, nil) -- remove original metatable
100     setmetatable(o, Response) -- bind Response methods
101     return o
102 end
104 --- get result code
105 [email protected] number
106 function Response:getCode()
107     return self.code
108 end
110 local bsnsPack = {}
111 bsnsPack.BsnsPack = BsnsPack
112 bsnsPack.Request = Request
113 bsnsPack.Response = Response
115 return bsnsPack



1. Line 1: This is a comment line

Lua’s line comment begins with two minus signs -,

Class notes: — @ class type [: parent_type {, parent_type}] [@ comment]

This is conducive to the vs Code prompt. For example, if you place the mouse over the place where the bsnspack appears in the code, a small pop-up window will prompt the key of this table and the type of key.

The annotations used more frequently are — @ class, — @ return, — @ param


2. In line 2, define a class called bsnspack (simulated by table).

There are no classes in Lua. Lua’s structured data type is called table, which is based on the key value structure. Map / dictionary relative to other languages. To access the value corresponding to the key of a table, click Can also be accessed with brackets []

There is no separate array structure in Lua, which is also based on table. The array subscript is key and the array element is value. It should be noted that the array subscript in Lua starts from 1.

The easiest way to create a table is to create an empty table with curly braces {}.

Lua is a scripting language. Variables do not need to specify types, but only need to be assigned values. Therefore, bsnspack = {maxserialno = 0,} is equivalent to defining a variable bsnspack, whose value is a table.

Lua’s variable is global by default. Lua code loaded into memory can access this variable. In order to avoid naming conflicts and accidental modifications, it is generally recommended that a variable be defined as a local variable to limit its scope. Add a local before the variable to define the local variable.

The scope of the bsnspack defined here is only in this file. Other files cannot be accessed. You can also use local to define local variables in functions and code blocks.


3. Line 7, give bsnspack a name__ The key of index is assigned to bsnspack

In Lua’s table__ Index is a special key, which is the key for Lua to implement classes and inheritance.
There is a concept in Lua called meta table. Lua defines some language default keys. These keys are generally associated with operators such as +, -, *, / and key access and value update. These keys are called meta methods (functions / methods in Lua can also be used as values). These meta methods are collectively called meta tables.

The method of setting meta table in Lua is in line 21 of the codefunction setmetatable(t, metatable), calling this method will make the parameter metatable become the meta table of parameter t.

After the meta table is set, the following occurs when accessing a key of parameter t in the code:

1) Lua first looks in t to see if there is a key. If there is, it returns the value of the key. Otherwise, execute 2)

2) Lua, see if the parameter} metatable is available__ The index key, if any, is in the__ Search in the value corresponding to index (_index value, if it is a table, search in this table; if it is a function, execute this function)

BsnsPack.__ Index = bsnspack. If other tables are set as meta tables, you can access all keys of # bsnspack. If the values of these keys are methods, these methods can be called.
So bsnspack can define method templates, which is similar to class. The data key defined by bsnspack is equivalent to the static field class field. The method key defined by bsnspack can be member method or class method, which will be described later

4. Lines 11-23, definitionsBsnspackA key called new whose value is a method

A code block in Lua does not use curly braces {}, and uses end as the end tag.

Definition methodFunction starts with a dot Or colon: split talbe name and method name,

The method defined with colon: will have a default parameter self, which is equivalent to the caller. If it is called externally with {bsnspack: new(), then self = = bsnspack. If it is called externally with a: new(), then self = = a.

Use some The defined method has no default parameters and can only explicitly write the parameter self.

Generally, use colon: to define the member method (for example, function bsnspack: setserialno (serialno) in line 23)

1) When calling {o: setserialno (serialno), self here is object O. only the serialno of object o is changed, and the serialnos of other objects are not affected.

Use some Define the method of constructing the object (such as , function bsnspack. New(), line 11), and the static method class method (such as , function bsnspack. Test(), line 69)

1) Elsewhere through bsnspack New() constructs the bsnspack object

1)Elsewhere through bsnspack Test() calls a class method

It is suggested that the method is defined with a colon:, called with a colon:, and defined with a point, Also use some when calling

The construction method is not necessarily called new, but just for unification. It is recommended to use new, which is consistent with other languages.

Method newLocal o = {}, and the defined keys are all member fields (each time the method bsnspack. New() is called, a new table is created and returned after initializing its fields)

Lua has no private member method. You can define the local method of the file and explicitly pass the object as the parameter self (for example, line 79)local function testPrivate(self)


5. Line 84, give classBsnspack definitionAn aliasRequestIn fact, it is to assign a table to another variable


6. Lines 87 to 102 define a classResponse, inheriting the base class bsnspack

Line 87, define the subclass response

In line 88, set the meta table so that the response can access all the keys of bsnspack (inherit all the methods of bsnspack)

In line 89, all objects can access all the keys of the response (including all the keys of bsnspack through recursion)

In line 94, initialize O by calling the bsnspack constructor. O is the object of bsnspack and has all the member fields of the base class

Line 97 defines the new field code of response relative to the base class

In lines 99 and 100, change the meta table of O to response, so that O can access all member methods of response (including all member methods of bsnspack through recursion)

Response can override the method of bsnspack

1 function Response:getPayload()
2     return self.payload
3 end

When accessing the key in Lua, first look it up in the table itself. If not, then look it up in the meta table, so the rewritten method will be called to realize polymorphism.


7. Lines 110 ~ 115, export the classes defined in this file.

Since the definition of class is a local variable defined in local mode and cannot be accessed externally, it should be regarded as the return value of the file return

If the file only exports one class, you can directly return this local variable (for example, if you only export bsnspack, return , bsnspack is OK)

Since this file needs to export three classes, they are exported in a table

Other files need to access the class of this file and need to callThe require method is imported. The parameter of the method is the path (excluding the suffix. Lua), and the return value is the return value of the Lua file

1 local bsnsPack = require("Assets.Lua.bsns.bsns_pack")
2 local Request = bsnsPack.Request
3 local Response = bsnsPack.Response


8. If you want modular management and expose all classes of a module to other modules through a file, you can define a local variable in this file, import the classes of all files of this module through require, assign values to keys with the same name as the class, and finally return this local variable

File BSNs lua

 1 local bsns = {}
 3 local bsnsPack = require("Assets.Lua.bsns.bsns_pack")
 4 bsns.Request = bsnsPack.Request
 5 bsns.Response = bsnsPack.Response
 7 bsns.BsnsMod = require("Assets.Lua.bsns.bsns_mod")
 8 bsns.BsnsCenter = require("Assets.Lua.bsns.bsns_center")
10 return bsns


5. Introduction to simple grammar

1) Statements in Lua do not need semicolons; ending

2) The basic data types commonly used by Lua include nil, Boolean, number, string, function and table

3) Get array variable for # array length, for example

1 local array = {"Lua", "Tutorial"}
2 local len = #array
3 print(len)

4) For traversing arrays

1 for i, v in ipairs(table) do
3 end

5) For traversing objects

1 for k, v in pairs(obj) do
3 end

6) For other grammars, please refer to the rookie tutorial


6. Lua code specifications are available for reference