How to Use Lua scripting language in Java

Source: Internet
Author: User

HowJavaUsed inLua scripting languageIs the content to be introduced in this article, mainly to learnLUA scripting languageInJAVAHow to use it,LuaNow it's popular, and the syntax is quite simple.JavaFor a long time, I recorded some things below for details.

LuaIs embedded in the C program, but the official does not support Java. I checked it onlineLuaJavaOpen-source library. I tried it and found that this library is relatively complete. The address is

 
 
  1. http://www.keplerproject.org/luajava/ 

This LuaJava is actually packaging Lua's C interface into a Java library through JNI according to Lua's official documentation. download, which is. dll,. jar. put. dll to java. library. path. put lib in classpath and run OK in helloworld.

However, during the test, we soon found the first problem: calling the LuaState. when the pushInteger method is used, the following Error occurs: Unsatisfied Link Error. other LuaState. the pushNumber method is correct. I used the Depends tool to check this. the dll does not export the pushInteger function. dizzy ....

Download the LuaJava source code and check Luajava. c and Luajava. h. I found a problem in it. In. h, I defined the C function corresponding to the Java function in JNI.

JNIEXPORT void JNICALL Java_org_keplerproject_luajava_LuaState _ 1 pushInteger

However, this function is not implemented in. c. It is speechless. It seems that there are all big tigers. Thanks to the source code, the implementation of this function is added to Luajava. c,

 
 
  1. JNIEXPORT void JNICALL Java_org_keplerproject_luajava_LuaState__1pushInteger  
  2.    (JNIEnv * env, jobject jobj, jobject cptr, jint i)  
  3. {  
  4.     lua_State * L = getStateFromCPtr( env , cptr );  
  5.     lua_pushinteger(L, i);  

Then compile. compilation has also encountered a problem. The official document says that you can use VC ++ for Build, but it does not say what version is officially used. I cannot use VC2005. fortunately, Luajava is relatively small. h. c. Create a new one in VC. dll project, add the file, modify the build parameter (Include needs to add the lua header file, lib needs to add lua. lib file, and select Compile as C Code (/TC) Build.

ThenJavaThe pushInteger method is no problem.

During the test, we found that in the documentation provided by Luajava, how to call Java objects/methods by Lua scripts is very detailed, but how to call the Lua function/obtain the return value in Java is not. referring to the Lua C document of http://www.lua.org/manual/5.1/manual.html#lua_CFunction, the code that transfers objects to Lua and gets the return value is realized:

Test1: Pass the simple type in the test and obtain the returned value:

Lua script (test. lua ):

 
 
  1. function test(a,b)  
  2.     return a+b  
  3. end 

Java code:

 
 
  1. Static {
  2. // Load Lua5.1.dll, because LuaJava still needs to call Lua.
  3. System. loadLibrary ("lua5.1 ");
  4. }
  5. Public static void main (String [] argu) throws LuaException {
  6. LuaState L = LuaStateFactory. newLuaState ();
  7.  
  8. L. openLibs ();
  9.  
  10. // Read The Lua script
  11. Int error = L. LdoFile ("test. lua ");
  12. If (error! = 0 ){
  13. System. out. println ("Read/Parse lua file error. Exit .");
  14. Return;
  15. }
  16. // Find the function test
  17. L. getField (LuaState. LUA_GLOBALSINDEX, "test ");
  18. // Parameter 1 pressure Stack
  19. L. pushInteger (1 );
  20. // Parameter 2 pressure Stack
  21. L. pushInteger (2 );
  22. // Call !! There are two parameters in total and one return value
  23. L. call (2, 1 );
  24. // Save the returned value to
  25. L. setField (LuaState. LUA_GLOBALSINDEX, "");
  26. // Read
  27. LuaObject l = L. getLuaObject ("");
  28. // Print the result.
  29. System. out. println ("Result is" + l. getString ());
  30. L. close ();
  31. }

Test 2: Passing Java objects

 
 
  1. class Value {  
  2.     public int i;  
  3.     public void inc() {  
  4.         i++;  
  5.     }  
  6.     public int get() {  
  7.         return i;  
  8.     }  
  9.     public String toString() {  
  10.         return "Value is " + i;  
  11.     }  

Lua Script: (this script calls the inc method of the object twice and calls the get method to output the result)

 
 
  1. function test1(v)  
  2.     v:inc();  
  3.     v:inc();  
  4.     print("In lua: " .. v:get());  
  5.     return v  
  6. end 

JavaCode: (the previous steps are the same, omitted)

 
 
  1. // Find the test1 Function
  2. L. getField (LuaState. LUA_GLOBALSINDEX, "test1 ");
  3. // Generate a new object for testing
  4. Value v = new Value ();
  5. // Object pressure Stack
  6. L. pushObjectValue (v );
  7. // Call the test1 function. At this time, one parameter and one return value
  8. L. call (1, 1 );
  9. // Put the result in B.
  10. L. setField (LuaState. LUA_GLOBALSINDEX, "B ");
  11. LuaObject l = L. getLuaObject ("B ");
  12. System. out. println ("Result is" + l. getObject ());

Running result:

 
 
  1. Result is Value is 2  
  2. In lua: 2 

As expected.

Create a monster, and pass the setting in lua as the initial state to monstor. The name is sample monstor, which defends against 10 attacks, 10 attacks, and 100 life.

1. Pilot into lib -- luajava-1.1.jar

 
 
  1. import org.keplerproject.luajava.LuaState;  
  2. import org.keplerproject.luajava.LuaStateFactory;  
  3.  
  4. public class Load{  
  5. LuaState luaState;  
  6. /**  
  7. * Constructor  
  8. * @param fileName File name with Lua .  
  9. */  
  10. Load(final String fileName) {  
  11. this.luaState = LuaStateFactory.newLuaState();  
  12.  
  13. this.luaState.openLibs();  
  14.    this.luaState.LdoFile(fileName);  
  15.  
  16. }  
  17. /**  
  18. * Ends the use of Lua environment.  
  19. */  
  20. void close() {  
  21. this.luaState.close();  
  22. }  
  23. /**  
  24. * Call a Lua inside the Lua to insert  
  25. * data into a Java object passed as parameter  
  26. * @param Name Name of Lua .  
  27. * @param obj A Java object.  
  28. */  
  29. void run(String Name, Object obj) {  
  30. this.luaState.getGlobal(Name);  
  31. this.luaState.pushJavaObject(obj);  
  32. this.luaState.call(1,0);  
  33. }  
  34. }  
  35.  
  36. public class Monster{  
  37. /* Info */  
  38. protected String race;  
  39. protected int defense;  
  40. protected int attack;  
  41. protected int life;  
  42. /* */  
  43. private Load ;  
  44. public Monster(String race) {  
  45. /* Loads Lua for this race.*/  
  46. this. = new Load(race+".lua");  
  47. /*Call Lua create .*/  
  48. .run("create", this);  
  49. }  
  50.  
  51. public void setRace(String race) {  
  52.    this.race = race;  
  53. }  
  54. public String getRace() {  
  55. return race;  
  56. }  
  57. public int getDefense() {  
  58. return this.defense;  
  59. }  
  60. public void setDefense(int defense) {  
  61. this.defense = defense;  
  62. }  
  63. public int getLife() {  
  64. return this.life;  
  65. }  
  66. public void setLife(int life) {  
  67. this.life = life;  
  68. }  
  69. public void setAttack(int attack) {  
  70. this.attack = attack;  
  71. }  
  72. public int getAttack() {  
  73. return this.attack;  
  74. }  
  75. }  
  76.  
  77. monstor.lua---  
  78.  
  79. create(monster)  
  80. monster:setRace("Sample Monster")  
  81. monster:setDefense(10)  
  82. monster:setAttack(10)  
  83. monster:setLife(100)  
  84. end 

However, this error is always thrown:

 
 
  1. PANIC: unprotected error in call to Lua API (Invalid method call. No such method.) 

I don't know why. research will be performed later.

It has been found that a method is missing in the Monster class:

 
 
  1. public void setRace(String race) {  
  2.    this.race = race;  

No wonder you cannot find it,

To import other lua files B. lua in lua File a. lua, use require "B"

If you want to obtain the return parameter after calculation from lua, You need to modify it: In the lua file, change it:

 
 
  1. create(monster)  
  2. monster:setRace("Sample Monster")  
  3. monster:setDefense(10)  
  4. monster:setAttack(10)  
  5. monster:setLife(100)  
  6. return monster  
  7. end 

Run in Load. java is changed to the following:

 
 
  1. Void run (String Name, Object obj ){
  2. This. luaState. getGlobal (Name );
  3. This. luaState. pushJavaObject (obj );
  4. This. luaState. call (1, 1); // a parameter, 0 returns
  5. Try {
  6. Object object = luaState. getObjectFromUserdata (1 );
  7. } Catch (LuaException e ){
  8. E. printStackTrace ();
  9. }
  10. }

Summary: howJavaUsed inLua scripting languageI 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.