Using LUA Scripting in Unity: Language layer and game logic glue layer Processing

Source: Internet
Author: User
Tags lua

Foreword: Why use Lua first to say, all programming language inside, my favorite is still c#,visualstudio+c#, can only say too comfortable. So why not use LUA in unity? may be mainly idle egg pain ..... There are other secondary reasons:
    • Easy to do function of hot update;
    • The depth and breadth of the Lua language is small, easy to learn and easy to use, can reduce project costs.
scenarios where C # and Lua invoke each other frankly, I don't have a close look at all the libraries that C # and LUA call each other now, presumably by searching for a few:
    1. Slua:https://github.com/pangweiwei/slua
    2. nlua:http://nlua.org/
    3. Unilua:https://github.com/xebecnan/unilua
    4. Ulua Plug-in
The specific content of these programs, not the focus of this article, here do not say, interested students, point to open their own to see on the line.
Finally, I chose the Ulua, the main reason is: Ulua scheme is relatively mature, it does not have much of their own code, mainly to the Luainterface and LUA interpreter integration, are relatively mature code, relatively stable. In addition, the individual appreciates luainterface this library. Next we'll take a look at Ulua. :) Ulua basic use of the Ulua plugin is very simple, basically look at his own several examples to understand.
The game logic glue layer Design Ulua plug-in solves the problem of the language level: C # and LUA two language code calls each other, as well as parameter passing and related to a series of underlying issues. In our game logic development, how to use Lua is a problem in the upper layer. Here is a solution I groped, personally think: simple enough, clear enough, is very thin and thin layer, can not be thinner.

How many luastate do you use? Once saw a Netizen's plan, each time runs the script to new one luastate, personally thinks this kind of plan is very inappropriate. The LUA code for the entire game should run on a luastate for two reasons:
    1. Lua code running on the same luastate can call each other. Believe that a game will always have a certain amount of code, if the code in different LUA files, completely independent operation, can not call each other or call each other very troublesome, the game logical organization adds a lot of obstacles;
    2. One of the principles of mixed-language programming is to minimize the language-context switching of code execution, because the cost of this is often much higher than what the code literally looks like. My goal: Since using LUA, try to put the upper-level logic of UI event response into LUA code.
For these reasons, I think the LUA code of the game is all running on a luastate. This is also the basis of this paper's plan.

Implementation Luacomponent First of all, say my goal:
    • Since C # is a scripting layer for unity, LUA should have the same logical status as C # script code;
    • The code for LUA integration should be minimal and should be kept as simple as possible;
Based on the above objectives, I implemented the Luacomponet class, it is implemented similar to Monobehavior, but we do not have C + + source code, only by the C # layer of Monobehavior to forward the call. In this way, our LUA code is implemented by writing and writing a C # Script component that is fully consistent, and can be said to achieve seamless integration with the engine. :) OK, first on the code!
Using unityengine;using system.collections;using luainterface;//////LUA component-The LUA script it invokes can implement functions like the Monobehaviour derived class//[Addcomponentmenu ("Lua/luacomponent")]public class luacomponent:monobehaviour{private static Luastate s_luastate;    Global LUA virtual machine [Tooltip ("Bound Lua Script path")] public textasset m_luascript;        Public luatable Luamodule {get;    Private set;    } luafunction m_luaupdate; The update function implemented by LUA, possibly NULL/////Find the Lua component (module object) bound to the Game object///public static luatable getluacomponent (Gameobject go) {luacomponent Luacomp = go. Getcomponent
  
   ();        if (Luacomp = = null) return null;    return luacomp.luamodule; }    ///
   /// Add a LUA component to a gameobject ///public static luatable addluacomponent (Gameobject go, Textasset luafile) {luacomponent Luacomp = go. AddComponent
   
    ();  Luacomp.initilize (Luafile);    Manually call the script to run to get the luatable return value of return luacomp.luamodule; }    ///
    ///For external manual LUA scripting interface ///public void Initilize (Textasset luafile) {m_luascript = Luafile;        Runluafile (Luafile); --Get the usual function callback if (this. Luamodule = null) {M_luaupdate = this.        luamodule["Update"] as luafunction; }    }    ///
    /// Invoke LUA virtual machine, execute a script file //    void Runluafile (Textasset luafile) {if (Luafile = = NULL | | | string.        IsNullOrEmpty (Luafile.text)) return;        if (s_luastate = = null) S_luastate = new Luastate ();        object[] Luaret = s_luastate.dostring (luafile.text, luafile.name, NULL); if (Luaret! = null && luaret.length >= 1) {//contract: The first returned Table object as the LUA module this.        Luamodule = luaret[0] as luatable;        } else {debug.logerror ("Lua script does not return Table object:" + luafile.name);        }}//Monobehaviour callback void Awake () {runluafile (m_luascript); Callluafunction ("Awake", this.    Luamodule, This.gameobject); }//Monobehaviour callback void Start () {callluafunction ("start", this.    Luamodule, This.gameobject); }//Monobehaviour callback void Update () {if (m_luaupdate! = null) M_luaupdate.call (this.    Luamodule, This.gameobject);  }    ///
    /// call a function in a LUA component //void Callluafunction (String funcName, params object[] args) {if (this.        Luamodule = = null) return; luafunction func = this.        Luamodule[funcname] as luafunction; if (func! = null) func.    Call (args); }}
   
  

This code is very simple and implements several function points:
    • Management of a global luastate;
    • Responsible for forwarding the Monobehavior call to the corresponding LUA function;
    • The Lua script version interface for Getcomponent () and addcomponent () is provided, which is very important.
LUA code conventions to work well with luacomponent, LUA scripts need to follow some conventions:
    • The Lua script should return a table, either the module for LUA or any table object;
    • The returned Table object should contain monobehaviour corresponding callback function;
For example:
Require "enginemain" local democomponent = {}function Democomponent:awake (gameobject) Debug.Log (Gameobject.name ... ") Awake ") Endreturn DemoComponent
In the luacomponent callback function, the Gameobject object is actively passed as a parameter to the LUA layer to facilitate its processing accordingly.
Mutual invocation between LUA components (in LUA code)

Based on the above structure, it is easy to implement mutual invocation between LUA components. In the demo project, there is a "Sphere" object that binds the following script:

Require "enginemain" local spherecomponent = {}spherecomponent.text = "Hello World" function Spherecomponent:awake ( Gameobject) Debug.Log (Gameobject.name ... " Awake ") Endreturn spherecomponent
There is another "Cube" object that binds the following script to demonstrate the invocation of the members of the LUA component above:

Require "enginemain" local democomponent = {}function Democomponent:awake (gameobject) Debug.Log (Gameobject.name ... ") Awake ") endfunction Democomponent:start (gameobject) Debug.Log (Gameobject.name ...") Start ")--demo luacomponent code calls to each other local Spherego = Gameobject.find (" Sphere ") Local Sphereluacomp = Luacomponent.getluacomponent (Spherego) Debug.log ("Sphere.luademob:"). Sphereluacomp.text) Endreturn DemoComponent


Full version Demo:

http://download.csdn.net/detail/neil3d/8583799

Http://pan.baidu.com/s/1bnk3ATD Password: pqih


Finally, let's summarize: in the design of the last game logic framework, the better idea is: Under the premise of a thorough understanding of unity's own architecture, the next layer of design under its architecture, rather than a new framework. Because unity itself is a framework.

Using LUA Scripting in Unity: Language layer and game logic glue layer Processing

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.