Rookie learning-Hot update in Unity-Luainterface User Guide

Source: Internet
Author: User
Tags lua

"Because of learning, so translate!" 】

1. Introduction

Luainterface is an integrated library between the Lua language and the Microsoft.NET Platform Common Language Runtime (CLR).

Very many languages already exist for the CLR compiler and CLR implementations, already available for Microsoft Windows, BSD operating systems, and Linux operating systems.

LUA is a programming language designed to extend applications, explaining the libraries that run and are very easy to embed. Specific information can be involved in Lua ' sreference manual.

The following sections describe how to compile and install Luainterface. Part 3rd includes the use of it in CLR applications, and section 4 describes the use in Lua scripting.

2. Installing Luainterface

Luainterface needs a LUA interpreter to work.

An interpreter for Lua5.0 has been included in the Luainterface release package, including Luainterface binaries under Mircrosoft windows and. NETCLR (LuaInterface.dll and Luanet.dll). You must copy Lua50.exe and Lua50.dll to your path directory, copy LuaInterface.dll to your global assembly cache. Luainterface uses Compat-5.1, so copy Luanet.dll to your package.cpath.
Compiling luainterface from source code is not difficult. The advertisement package includes a project file to compile the luanet. It is under Visual Studio. Net 2003. The compilation script used to compile is under visual Studio 6.

You can simply compile all src/luainte to get LuaInterface.dll.

3. Using LUA under the CLR

The CLR application uses the LUA interpreter through the Luainterface.lua class. Instantiate this class. Create a new LUA interpreter, and the different instances are completely independent. The Lua class index creates, reads and changes all variables, indexed by the name of the variable, as shown in the following demo example (cable

The fuse always returns an object that must be cast to the correct type):
Code:

Start a lua Interpreterlua lua = new Lua ();//Create Global variables "num" and "str" lua["num"] = 2;lua["str"] = "a str ing ";//Create an empty Tablelua. NewTable ("tab");//Read Global variables "num" and "str" Double num = (double) lua["num"];string str = (string) lua["str"];


The Dostring and Dofile methods run the Lua script. This method returns an array when the script returns a value. Such as
Code:

Execute a Lua script Filelua. Dofile ("Script.lua");//Execute chunks of Lua Codelua. Dostring ("num=2"); Lua. Dostring ("str= ' A String '");//LUA code returning valuesobject[] Retvals = Lua. Dostring ("return num,str");

Luainterface himself to convert Lua's nil to the CLR's null,strings to System.String. Numbers to System.double,booleans to System.Boolean. Tables to luainterface.luatable. Functions to Luainterface.luatable, and vice versa. UserData is a special case: Clrobjects does not have a matching LUA type. The UserData is converted back to the original type when passed to the CLR. Luainterface convert other UserData to Luainterface.luauserdata.
Luatable and Luauserdata objects have indexes to read and alter fields, and to index them using strings or numbers. The Luafunction and Luauserdata objects include a call method to run the function. Include the number of parameters.

The return value is in an array.
At last. The Lua class has a registerfunction function to register a CLR function as a global LUA function. Its parameters include the function name, the target function, and the methodinfo of the representation method. such as Lua. Registerfunction ("foo", Obj,obj. GetType (). GetMethod ("foo")) has registered the Foo method of object obj as the Foo function.

4.lua using the CLR

This section includes initializing and using CLR objects in Lua scripts, running through the LUA interpreter, or running in a CLR application. All of the following examples are LUA languages.


4.1 Loading CLR types and instantiating objects

In order to instantiate an object, the script requires a type reference. Static fields are used statically, static methods are called statically methods the same also requires a type reference. To obtain a type reference, the script file first needs to be added

Load a assembly that includes the specified type. Through the load_assembly function. Then use the Import_type function to get the reference. The following examples show how to use these two functions:
Code:

Require "luanet"--Loads the System.Windows.Forms and System.Drawing assembliesluanet.load_assembly (" System.Windows.Forms ") luanet.load_assembly (" System.Drawing ") Form = Luanet.import_type (" System.Windows.Forms.Form ") point = Luanet.import_type (" System.Drawing.Point ") – structure--Loading an enumerationstartposition = Luanet.import _type ("System.Windows.Forms.FormStartPosition")

Invokes the type reference of the instantiated object. Luainterface uses the first constructor that satisfies the number and type of parameters, because there are overloaded constructors, the matching process converts numeric strings to numbers, numbers to characters

String, assuming necessary, the number of numbers in Lua is converted to the corresponding CLR number type.

Get constructor Bysig returns a constructor for a given type and constructor for the signa-ture of a constructor (a type reference to the type of the function's shape). Called to return the object instantiated by the constructor. The following demo sample demonstrates different ways to instantiate a CLR object:
Code:

--SomeType is a reference to a type with the following constructors--1. SomeType (String)--2. SomeType (int)--3. SomeType (int,int) obj1 = SomeType (2,3)--instantiates SomeType with constructor 3obj2 = SomeType ("x")--instantiates Some  Type with constructor 1obj3 = SomeType (3) – Instantiates SomeType with constructor 1int32 = Import_type ("System.Int32")-- Gets the SomeType constructor with signature (Int32) Sometype_cons2 = Get_constructor_bysig (sometype,int32) obj3 = Sometyp E_CONS2 (3)--instantiates SomeType with constructor 2
4.2 Using fields and methods

A field in a script that can use a CLR object, with the same syntax as indexing data from a table. The data written to the field is converted in order to the type of the corresponding field, the number assigned to the Int32 field is converted to Int32. No indexed genus

Sex is also used as a field.

Luainterface has a simple way to index a one-dimensional array. such as arr[3]. Multidimensional arrays need to use the method of the array class.

The script is able to invoke the object's method, which, like the method that invokes table, passes the first number of parameters of the object. Use the ': ' operator. You can use the get and set methods to use indexed properties (usually get PropertyName and set PropertyName):


Code:

--Button1, Button2 and Form1 are the CLR objectsbutton1. Text = "OK"; button2. Text = "Cancel"; Form1. Controls:add (button1); Form1. Controls:add (button2); Form1:showdialog ();


LUA has only function calls by value, so when a script calls a method that uses an out or ref parameter, LUAINTERFACE returns the output value of those parameters, along with the return value of the method. In the method call, the out-participating

The number should be omitted, as seen in the following example:
Code:

--Calling int obj::outmethod1 (int,out int,out int) retval,out1,out2 = obj:outmethod1 (inval)--calling void Obj::O UTMETHOD2 (int,out int) retval,out1 = OBJ:OUTMETHOD2 (inval)--retVal seránil--calling int obj::refmethod (int,ref int) ret VAL,REF1 = Obj:refmethod (INVAL,REF1)


Suppose a method is overloaded, the first number of matching parameters, the version number of the type, is called. Ignores out parameters. The following example shows how a script can invoke the overloaded SomeMethod method of a sometype with a different version number.
Code:

--Versions of sometype.somemethod:--1. void SomeMethod (int)--2. void SomeMethod (String)--3. void SomeMethod (Othertype)--4. void SomeMethod (String,othertype)--5. void SomeMethod (Int,othertype)--6.  void SomeMethod (Int,othertypesubtype)--Obj1 is instance of sometype--Obj2 are instance of othertype--Obj3 is instance of Othertypesubtypeobj1:somemethod (2)--version 1obj1:somemethod (2.5)--version 1, round Downobj1:somemethod ("2")--Vers Ion 1, converts to Intobj1:somemethod ("X")--version 2obj1:somemethod (OBJ2)--Version 3obj1:somemethod ("X", Obj2)--Vers Ion 4obj1:somemethod (2,OBJ2)--version 4obj1:somemethod (2.5,OBJ2)--version 4, round Downobj1:somemethod (2,obj3)--ver Sion 4, cast--versions 5 and 6 never get called 


There is also the case of a function Get_method_bysig where a method has a version number that is never called. Given an object or type reference and method signature signature (the name and type of the method), the function returns with that signature. The following example shows the method that is seen:
Code:

--Versions of sometype.somemethod:--5. void SomeMethod (Int,othertype)--Obj1 is instance of sometype--Obj2 is instance of OtherTypeInt32 = Luanet.import_type (' S Ystem. Int32 ') Somemethod_sig5 = Luanet.get_method_bysig (obj1, ' SomeMethod ', Int32,obj2:gettype ()) Somemethod_sig5 (obj1,2, OBJ2)--Calls version 5

If a method or field name is a reserved keyword for LUA, the script can still use them. by obj[the "name"] syntax. Assuming that an object has 2 methods that use the same signature but belong to different interfaces, such as Ifoo.method () and Ibar.method (), then the tag obj["Ifoo.method" (obj) calls the first version number.
Luainterface throws an exception when a Run method error occurs, with an exception object with an error message. Assuming the script wants to catch an error, it must use Pcall to invoke all methods.

4.3 Handling events


The events in the Luainterface have an add and a Remove method, which are used to register and cancel the registration event processing, respectively. Add takes the Lua method as the number of references. Convert it to the CLR corresponding delegate managed method and return. Remove takes the event handling delegate hosting as the parameter. Remove the processor, such as the following:
Code:

function Handle_mouseup (Sender,args) print (Sender:tostring (): ' mouseup! ') button. Mouseup:remove (handler) Endhandler = button. Mouseup:add (Handle_mouseup)


The script can use the Add and remove methods of the event object to register event handling (usually add EventName and remove EventName), but add does not return a delegate managed object. It is therefore not possible to cancel the register after the function has been registered in this way.

4.4 Managed delegates and sub-class subtyping


Luainterface provides methods for dynamically creating types in 3 to extend the CLR.
The first one has been talked about in the context of the event handler: where the estimate is entrusted through the Lua function. Luainterface creates a new commit type and passes it to the CLR.


Another way is to pass a LUA table. The interface is implemented. Luainterface creates a new type of interface implementation. This type of object method is managed to the table. For example, the following:
Code:

--Interface Isample {int dotask (int x, int y);} --Sometype.somemethod Signature:int SomeMethod (isample i)--obj is instance of sometypesum = {}function sum:dotask (x, y) r Eturn x+yend--sum is converted to instance of isampleres = Obj:somemethod (sum)


Assuming that there are overloaded functions in the interface, all version number functions are managed into a LUA function, which determines which version number is called depending on the type of the reference. Luainterface cannot pass out parameters to a function, but the function must return the output values of these and ref parameters together, such as the following
Code:

--Interface ISample2 {void DoTask1 (ref int x, out int y);--int DoTask2 (int x, out int y);} --Sometype.somemethod Signature:int SomeMethod (isample i)--obj is instance of sometypeinc = {}function inc:dotask1 (x) re Turn x+1,xendfunction inc:dotask2 (x) return x+1,xendres = Obj:somemethod (sum)


The last way to create a new CLR type is to subclass the already existing class, using LUA table's functions to rewrite some or all of its virtual methods (assuming that LUA table does not override the original version number used by the method Luainterface).

The table function calls a function of the parent class through a field named base.

To turn a table into an instance of a subclass. The script must call the Make_object function. Table and the class type reference that will create the subclass as a parameter.

The following demo sample shows how to create a subclass: For example, the following:
Code:

--Class Someobject {--Public virtual int SomeMethod (int x, int y) {return x+y;}} --Sometype.somemethod signature:int somemethod (someobject o)--obj is instance of sometypesome_obj = {Const = 4}functi On Some_obj:somemethod (x, y) Local z = Self.base:SomeMethod (x, y) return z * self.constendsomeobject = Luanet.import_type (' Someobject ') luanet.make_object (some_obj,someobject) res = Some_obj:somemethod (2,3)--Returns 20res = Some_obj: ToString ()--calls base Methodres = Obj:somemethod (some_obj)--passing as argument


During the implementation of the interface application in the subclass, there is the same problem about overloading and out/ref parameters. Finally, the Free_object function has a table parameter called by the polygon Make_object, serving the connection of the table and the CLR subclass instance. The script must use this method before discarding the reference to table, or it will cause a memory leak.


Finish

Application:

"USAGE"
Import the resource bundle and then copy the Plugins directory under the ' ulua/plugins/' path to assets and add the Luainterface namespace to your script to see some basic usage in examples. The main code is very readable (Lua.cs) and Luainterface manual.

"Lua ' require ' or ' dofile '"
In order to import a file that requires the and/or Dofile file, you must have the text asset placed in the root directory of your project ' Assets/resources '. It must be named *.lua.txt '.
Like what:
' Assets/resources/mydir/myscript.lua.txt '

Then, in your LUA code, you can ask for:
' Require ("Mydir/myscript.lua") '

1 " Download the resource bundle to Ulua. Import in Project. Follow the instructions to copy the contents of the plugins directory into the plugins directory of project;

(This step may appear to be unable to find DLL error, I am here to restart Unity resolved)

After you import the project, the root directory has the following things:

2 " write some Lua scripts in the. txt file. Example:

(Note: The suffix name for the. txt script here is ". txt")

3 " load the. txt file that contains the Lua script into the game and the resource type is" Textasset ":

Method Optional, for example:

The ① is placed in the resources directory. Resources.load () to load;

② put it in a casual place in project. Use Resoueces.loadatpath () to load.

③ into Assetbundle and put it on the file server. Use WWW to load asynchronously.

(If you use ③, it is convenient to recommend a virtual file server with a name called "HFS".) Just a little bit, you can simulate a file server to come out:

。 Very useful)

4 " parse Lua script:

1 luastate ls = new Luastate (); 2 ls.              Dostring (luastring); Luastring is the character that is loaded into the document. The type is string3 luafunction lf = ls.  GetFunction ("Luafunc"); Luafunc is the method name written in the Lua script 4 object[] r = LF.            Call ("2"); The "2" in parentheses is the value of the integer operation to be passed to the method in Lua 5 return r[0].              ToString (); R[0] is the value returned after the operation, and the type is object. Before use, you need to turn the type

Very easy. In summary, the relationship between Lua and C # in Unity3d. Each passing method and the number of references. It's OK.

You will see that there is really an external logic that works in a running game.

Rookie learning-Hot update in Unity-Luainterface User Guide

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.