Use the Lua Script Engine kahlua in JAVA (j2s)

Source: Internet
Author: User

InJAVAUsingLua scriptEngine kahlua is the content to be introduced in this article, mainly to learn how to use it in JAVSLUA,LuaWe were lucky to have been selected by blizzard, and we have made a lot of applications in Warcraft, which has achieved extremely fast development,LuaTherefore, it has become a game and software developmentScriptThe preferred language.LuaIs a very conciseScriptLanguage, but it is not very easy to write. Of course, too much simplification makes the program itself a bit messy. There are a lot of language tutorials on the Internet, so I will not talk about them here.

Kahlua was originally designed for j2s and has now been extended to J2SE. The project address is http://code.google.com/p/kahlua/. here we can download the source code and compiled jarpackages. In practical applications, I found it very difficult to import jar packages in j2s. After several days of failure, I had to put the source code in the project directory for compilation. Kahlua can identify *. lua and *. lbc files. *. lbc is the compiled lua file. This file is generally used in projects because it will not disclose the content of the lua file. You can download a lua runtime environment on the http://www.lua.org, after installation will automatically add the installation path to the system variable, then run the luac program in cmd can compile the script, the command is luac-o f. lbc d: \ f. lua. For more information, see the help documentation.

Under my account, kahluais the source code package of kahlua-release-20090611.zip. After decompression, it is an Ant project. Copy the content in the src directory and the stdlib. lua (lbc) file in the resource to the src project. Before programming, note that when specifying the file path in the program, pay attention to the location of the corresponding project file. The src folder of my project corresponds to the root directory of the program, for example,/src/stdlib. lua in the program is/stdlib. lua.

A unique data type in lua scripting language is a table. Tables are actually map and hash tables in java. For example, the following table:

 
 
  1. T1 ={} -- Define an empty table
  2. T1 [1] = 10 -- Define the table content
  3. T1 ["John"] = {Age = 27, Gender = "Male "}

Every script file is actually a large table, and every variable and method is a member of the table. Therefore, the script variables are global by default, and the methods can also be set as variables, kahlua is based on this concept.

1. Initialization:

 
 
  1. LuaState state=new LuaState(System.out);  
  2. UserdataArray.register(state);  
  3. OsLib.register(state);  
  4. LuaCompiler.register(state); 

The se. krka. kahlua. vm. LuaState object is the core of the kahlua engine. All operations are done by it, and some registration is performed after the LuaState object is generated.

2. Obtain a global table:

 
 
  1. LuaTable table = state. getEnvironment ();
  2.  
  3. LuaTable has a series of functions to add and obtain script content. The most common ones are:
  4. Void rawset (Object key, Object value); // Add content
  5. Object rawget (Object key); // get content

3. Load the script:

 
 
  1. InputStream is = this. getClass (). getResourceAsStream (scriptName );
  2. // ScriptName indicates the path of the script file.
  3. LuaClosure closure = LuaCompiler. loadis (is, "lua", table );
  4. // LoadCompiler is the compiler and loadis the method for loading input streams
  5. // Is the input stream; "lua" is the name of the compiler, as if any string is allowed; table is the global table
  6. // LuaClosure is the compiled statement of the script.

After the script is compiled, it is equivalent to a large method and added to the global table.

4. Execute the script:

 
 
  1. Sate. call (closure, null );
  2. LuaState's public Object call (Object fun, Object [] args)

The method is used to execute the method in the global table. As mentioned above, the whole script is saved to the global table as a method after compilation. Therefore, you can use this method to execute the script.

5. Method:

In public Object call (Object fun, Object [] args), fun is the function Object, and args is the parameter.

1) Call The Lua method in Java

 
 
  1. state.call( table.rawget("say") , new String[]{"Hello!"}); 

That is, the function is retrieved from the global table and executed.

2) Call the Java method in Lua

First, generate a class that inherits the JavaFunction interface and add it to the global table.

JavaFunction only has one public abstract int call (LuaCallFrame callFrame, int nArguments) method. callFrame is used to obtain input parameters and specified return values, and nArguments is used to obtain the number of input parameters. The return value is the number of returned parameters, because the lua function can have multiple return values.

 
 
  1. Class JavaFunctionSay implements JavaFunction {
  2. Public int call (LuaCallFrame frame, int arg ){
  3. String str = BaseLib. rawTostring (frame. get (0); // obtain the input parameter
  4. Say (str); // execute the corresponding Java content
  5. Frame. push ("result"); // return parameters
  6. Return 1;
  7. }
  8. }

Add table. rawset ("say", new JavaFunctionSay (); to the global table. Then you can use the say method in the corresponding Lua script.

Note:

Kahlua has a problem displaying Chinese characters. The encoding is incorrect. Modify String newstring (byte [] chars, int offset, int len) in LexState) the first line of the method is encoded as "GBK.
I encountered an error when using lbc generated by luac in windows .. if the file does not support Chinese characters, an error will be reported, and the English language will pass smoothly. It may be related to character encoding... to use Chinese Characters in lbc, you can use the following methods:

 
 
  1. File luasher = new File ("E: \ getWeather. lua"); // -- it doesn't matter what suffix name
  2. File lbcscript = new File ("C: \ Users \ Xinfeng boy \ getWeather. lbc ");
  3. Closure = LuaCompiler. loadis (new FileInputStream (luasstream), "Xin Feng boy", table); // "Xin Feng boy" is a random string. Its function is to indicate the scope.
  4. OutputStream OS = new FileOutputStream (lbcscript );
  5. Closure. prototype. dump (OS); // write the lbc format bytecode file to "C: \ Users \ Xinfeng boy \ getWeather. lbc.
  6. OS. close ();

When secondary calls are made

 
 
  1. File lbcscript = new File ("C: \ Users \ Xinfeng boy \ getWeather. lbc ");
  2. Closure = LuaPrototype. loadByteCode (new FileInputStream (lbcscript), table );

Ps: kuhlua does not support the gfind function. You must use the find function ps: kuhlua does not support the gfind function. You must use the find function.

Summary: This article describes how to use the Lua Script Engine kahlua in JAVA (j2s). I hope this article will help you!

Related Article

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.