[Unity3d] Unity3d game development of Lua and the game's indissoluble Bond (middle)

Source: Internet
Author: User
Tags lua

--------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------

Like my blog Please remember my name: Qin Yuanpei , my blog address is Blog.csdn.net/qinyuanpei.

Reprint please indicate the source, this article Qin Yuanpei , this article source:http://blog.csdn.net/qinyuanpei/article/details/39910099

--------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------

Hello everyone, I am Qin Yuanpei, welcome everyone to pay attention to my blog, my blog address is Blog.csdn.net/qinyuanpei. In the previous article "The Unity3d game development Lua and the game puzzle

The Edge (above), bloggers lead us to explore the relationship between the Lua language and the game development field, so let's continue to do the Lua language in the end today! With previous learning, we know that the purpose of designing the Lua language is to embed Lua in the application, providing flexible extension and customization capabilities for the application. The LUA language itself does not provide a rich library of classes as in other languages, so the Lua language must rely on other languages to do the functional expansion (but it is the functional sacrifice that will replace Lua's streamlined and stable core). If we want to learn more about the Lua language, we have to understand the interface between the Lua language and other languages, as this will be the basis for our use of the Lua language. So, today let the blogger to lead you to learn the Lua language and other language interaction bar!


One, Lua stacks

If we want to understand the nature of the Lua language interacting with other languages, we need to understand the LUA stack first. In short, the Lua language is able to interact with C + +, mainly because of a ubiquitous virtual stack. The stack is characterized by advanced, in the Lua language, the LUA stack is an index can be a positive or negative structure, and a positive number 1 always represents the bottom of the stack, negative-1 forever represents the top of the stack. In other words, without knowing the stack size, we can get the bottom element through index-1 and get the top of the stack by index 1. Below, we use an example to deepen our understanding of this passage:

 #include < Iostream>extern "C" {#include "lua.h" #include "lualib.h" #include "lauxlib.h"}using namespace Std;int Main () {//Create Lua    Environment lua_state* L=lua_open (); Open the LUA standard library, common standard libraries are luaopen_base, Luaopen_package, luaopen_table, Luaopen_io,//luaopen_os, luaopen_string, Luaopen_    Math, Luaopen_debug lual_openlibs (L);    Press into a digital lua_pushnumber (l,20);    Press into a number lua_pushnumber (l,15);    Press into a string Lua lua_pushstring (L, "Lua");    Press into a string C lua_pushstring (L, "C");    Gets the number of stack elements int n=lua_gettop (L);    Traverse the stack for each element for (int i=1;i<=n;i++) {cout << lua_tostring (L, i) << Endl; } return 0;} 

In the above code, we can see that we first created a variable l of type lua_state, which we can interpret as a context for the LUA runtime environment, where we have four elements pressed into the LUA stack: 20, 15, "Lua", "C" Then output it, if you understand the index in the Lua stack, the result of the final output should be:20, 15, "Lua", "C", because index 1 always points to the bottom of the stack, the first stack of elements will be at the bottom of the stack. So when we output the elements in the stack in ascending order of index, it is actually the bottom-up output, so that we can get the result.

Well, if there's nothing wrong with this code, then let's talk about the interfaces that Lua provides to C + +, which are all defined in the Lua.h file. Most of the C + + interfaces provided by LUA are related to stack operations, so an in-depth understanding of the LUA stack is a key and difficult point to learn the Lua language. Through the knowledge of data structure, we can know that the stack has a stack and into the stack of two basic operations, LUA provides the C API in the stack can be implemented by the push series method, as shown in:


And the way out of the stack or query can be achieved by the method of the to series, such as:


These two parts are the things that you must learn from the Lua language, because later if we need to integrate LUA into other projects, these things can be said to be the original reason, the core of the material. Well, let's use the API here to transform a sample code that adds a judgment on the type of elements in the stack:

#include <iostream>extern "C" {#include "lua.h" #include "lualib.h" #include "lauxlib.h"}using namespace Std;int    Main () {//Create LUA Environment lua_state* L=lua_open (); Open the LUA standard library, common standard libraries are luaopen_base, Luaopen_package, luaopen_table, Luaopen_io,//luaopen_os, luaopen_string, Luaopen_    Math, Luaopen_debug lual_openlibs (L);    Press into a digital lua_pushnumber (l,20);    Press into a string of Lua_pushnumber (l,15);    Press into a string Lua lua_pushstring (L, "Lua");    Press into a string C lua_pushstring (L, "C");    Gets the number of elements in the stack int n=lua_gettop (L);            Traverse the stack for each element for (int i=1;i<=n;i++) {//type to determine switch (Lua_type (l,i)) {case lua_tstring:          cout << "This value ' s type is string" << Endl;          Break          Case Lua_tnumber:cout << "This value ' s type is number" << Endl;        Break    }//Output value cout << lua_tostring (L, i) << Endl; }//Release Lua lua_close (L);}

Second, LUA interacts with C + +

the interaction of LUA and C + + from the choice of host language can be divided into C + + calling Lua and Lua calling C + + two types:

1. C + + calls Lua

When using C + + to invoke Lua, we can direct LUA scripts directly from the LUA environment in C + +, for example, we define a LUA script file externally, and now we need to use C + + to access the script. Here we can use the two methods of Lual_loadfile (), Lual_dofile (), the difference is that the former only load the script file, the latter will be loaded while the script file is called. Let's take a look at the following code:

#include <iostream>using namespace std; #include <iostream>extern "C" {#include "lua.h" #include "lualib.h" #    Include "Lauxlib.h"}using namespace Std;int Main () {//Create LUA Environment lua_state* l=lual_newstate (); Open the LUA standard library, common standard libraries are luaopen_base, Luaopen_package, luaopen_table, Luaopen_io,//luaopen_os, luaopen_string, Luaopen_    Math, Luaopen_debug lual_openlibs (L);    The following code can use Lual_dofile () to replace//load Lua script lual_loadfile (L, "Script.lua");    Run Lua script lua_pcall (l,0,0,0);    The variable arg1 is pressed into the stack top Lua_getglobal (L, "arg1");    The variable arg2 is pressed into the stack top Lua_getglobal (L, "arg2");    Reads the value of arg1, arg2 int arg1=lua_tonumber (L,-1);    int Arg2=lua_tonumber (L,-2);    Output two variables in Lua script cout << "arg1=" <<arg1<<endl;    cout << "arg2=" <<arg2<<endl;    Press the function printf into the stack top Lua_getglobal (L, "printf");    Call the printf () method Lua_pcall (l,0,0,0);    The function sum is pressed into the stack top Lua_getglobal (L, "sum");    Incoming parameter Lua_pushinteger (l,15);    Lua_pushinteger (l,25); Call the printf () method Lua_pcall (l,2,1,0);//Here are 2 parameters, one return value//output summation result cout << "sum=" <<lua_tonumber (l,-1) <<endl;    Press table tables into stack top Lua_getglobal (L, "table");    Get table lua_gettable (l,-1); The first element in the output table is cout << "table.a=" <<lua_tonumber (l,-2) <<endl;}
In this code we call an external file Script.lua. This is a LUA script file, in the debugging phase, we need to place it in the same directory as the C + + project source file, and in the formal run phase, we only need to put it and the final executable file in the same directory. Here's the script code:

--Define two variables in Lua arg1=15arg2=20--define a table table={a=25 in Lua    ,    b=30}--define a summation method in Lua function sum (A, B)  return a +bend--defines an output method in Lua function printf ()  print ("This is a function declared in Lua") end
We note that in the script file we define variables and methods, in C + + code We first use the Lua_getglobal () method to say that the variables or functions in the LUA script are pressed into the top of the stack, so that we can use the relevant to series method to get them, because each executionLua_getglobal () is at the top of the stack because we use the index value-one to get the element at the top of the stack. C + + can call a method in Lua, the first step is the same as the normal variable, is to push the method defined in Lua into the top of the stack, because only in the stack, we can use this method, next, we need to pass the push series method for the method in the stack to pass parameters, in the completion After the parameter is passed in, we can use a Lua_pcall () method to execute the method in the stack, it has four parameters, the first parameter is the LUA environment state lua_state, the second parameter is the number of arguments to pass in, the third parameter is the amount of the value to return, and the fourth parameter generally defaults to 0. Because LUA supports returning multiple results, we can take advantage of this feature of LUA to return multiple values. After executing the method, the result is pushed into the top of the stack, so we can index the value-to get the result of the function. If the function has more than one return value, the return order is defined in the function, in the stack, and the index value 1 represents the last return value. Well, that's the specific implementation of C + + calling Lua.

2. Lua calls C + +

First we define a method in C + +, which must take lua_state as the parameter, and the return value type is int, which indicates the number of values to return.

The static int averageandsum (Lua_state *l) {//returns the number of elements in the stack int n = lua_gettop (L);//The sum of the elements that are stored as double sums = 0;for (int i = 1; I <= N; i++) {    //parameter type processing if (!lua_isnumber (l, i)) {    //Incoming error message lua_pushstring (L, "incorrect argument to ' average '); Lua_ Error (L);} Sum + = Lua_tonumber (L, i);} Incoming average Lua_pushnumber (L, sum/n);//Incoming and Lua_pushnumber (l, sum);//The number of return values, here is 2return 2;}
Next we use the Lua_register () method in C + + to complete the registration of the method

  Lua_register (L, "Averageandsum", averageandsum);
So that we can use this method in the LUA environment, provided that the definition must be done before executing the code, we add a call to the method under the Lua script file:

--Call the method defined and registered in C + + in Lua average,sum=averageandsum (20,52,75,14) print ("average=". Average) Print ("sum=". Sum)
If we need to see the results of this method call in C + +, this is the same as calling Lua in C + +. Well, the interaction between C + + and Lua is finally over, and the code has been tangled for days, and it's finally clear. Of course, this is just a learning and understanding of the principle, if you want to better use LUA call C + +, it is recommended to understand these projects:

Luaplus, Luabind. I believe you will have a better understanding of how the methods in C + + are bound in Lua.



Third, LUA interacts with C #

Now that we know how C + + interacts with Lua, in theory we can continue to run the previous work in C # by writing DLLs, but doing so requires a lot of time to tangle between three languages, because it makes debugging more difficult. There was a coco2dx friend complaining about going back and forth between C + +, Javascript, and Lua, and I didn't feel anything at the time, because I was in the most difficult situation when C # and Java projects mixed up, and now I'm really feeling it, is that karma? Haha, well, not to mention this, fortunately, C # and Lua have a better solution to the interaction, in the open source community we can find a lot of support in C # to call Lua's tool library, bloggers here to recommend is luainterface this open source project, I found two addresses for this open source project:

1, Https://github.com/Jakosa/LuaInterface

2, Http://code.google.com/p/luainterface

Bloggers personally feel that this should be the same project, because the source code for two projects is the same, but the project downloaded from GitHub will error when used, it is estimated that the LUA version of my computer and the version of the LUA used in its project is inconsistent. The following project is available, and bloggers write a simple example here:

------------------------------------------------------------------------------//<summary>// This is a simple program to demonstrate the luainterface, through luainterface we can achieve in C # and LUA//communication with each other. Lua is a lightweight and efficient language that can be used in combination with any language. The Lua language was not originally created for game development, but was famous for game development. Currently, there are a lot of games in the world that use LUA as its//scripting language. Unity uses C # as its language, and Lua plays a significant role in the game development arena. The method of using Luainterface is as follows://1.c#//Registered LUA Callable method://Mlua.registerfunction (Lua invokes method name, class, class. GetMethod (C # method name));//NOTE: C # does not To use method-level generics, void fun<t> (String str), if used, the system automatically determines that T is the type of the first parameter. Load LUA code//mlua.dostring (LUA code);//Mlua.dofile (LUA file absolute path);//Call Lua method//Mlua.getfunction (Lua method).  Call (parameters); Note: This parameter does not pass a class of dynamic type, otherwise LUA cannot get the property value//2.lua//call C # method needs to be registered and processed according to Lua method//</summary>//---------------------- --------------------------------------------------------using system;using luainterface;namespace luaexample{ Public class luascript{//defines the Luafile property for the purpose of calling a LUA script from outside the private string Mluafile;public string Luafile {get {return mluafile;} set {mluafile = value;}}//lua Virtual Machine Private Lua mlua;//constructor public Luascript () {//Initialize LUA virtual machine mlua=new lua ();//Register printf Method Mlua.registerfunction (" Printf, "This,this. GetType (). GetMethod ("Printf"));} Define a C # method for Lua to use public void Printf (String str) {Console.WriteLine ("This method was invoked by Lua:" + str);} Call the Lua method in C # public void Dofile () {if (mluafile!= "")//execute the code in the Lua script mlua.dofile (mluafile);} Call the Lau method in C # public void dostring () {//The Lua script that is defined as a string mfuncstring= "function Add (A, B) io.write (a+b) end";// Define the method Mlua.dostring (mfuncstring) in LUA;//Call the method Mlua.getfunction ("Add"). Call (4,8);} Call the C # script in Lua public void Invoke () {//Call the registered printf method mlua.getfunction ("printf"). Call ("Hello Lua");}}}
Next we write a main class to invoke this class:

Using system;using luainterface;namespace luaexample{class mainclass{public static void Main (string[] args) {// Instantiate Luasxriptluascript mlua=new luascript ();//Set luafilemlua.luafile= "D:\\test.lua";//Invoke the Lua method defined in the string mlua.dostring ( );//For aesthetics consider adding a blank line Console.WriteLine ();//execute the script defined in the Lua file Mlua.dofile ();//Call the method defined in C # Mlua.invoke ();}}
Well, the interaction between C # and Lua solves, and more content is expected to be found in the project source code. All right, let's do it!

iv. LUA interacts with Java

a similar point in C # is that in Java we can use JNI to invoke C + + code, so that in theory Lua and Java should be able to interact through JNI, which is not currently being researched by the blogger. Here are just a few of the recommended libraries for you:

1,Luajava

2, Luaj


v. Conclusion

Okay, well, for a few days to study the LUA API, it feels like a little bit more. Because C + + research is not a lot of things, so like compiling C + + projects, configuration C + + environment, reference C + + library and header files these problems before the Assembly, this unexpectedly all of a sudden learned, Bo master recommended that you use codeblocks this C/d development environment, It's built-in GCC compiler I think it's not bad, and it cross-platform Ah, later work may be under the Linux and Mac development, choose a cross-platform editor or IDE, for us is not a good thing, because learning new things always cost a certain amount of money. Well, today's content is like this, I hope you like Ah, hee, and suddenly feel this article is very long ah.


Daily Proverbs: do not always because of accommodation others wronged themselves, this world few people are worth you always bent over. Stooping for a long time, will only make people accustomed to your low posture, you are not important.




--------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------

Like my blog Please remember my name: Qin Yuanpei , my blog address is Blog.csdn.net/qinyuanpei.

Reprint please indicate the source, this article Qin Yuanpei , this article source:http://blog.csdn.net/qinyuanpei/article/details/39910099

--------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------



[Unity3d] Unity3d game development of Lua and the game's indissoluble Bond (middle)

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.