Java中使用Lua脚本语言2

实现一个怪物的创建,把lua里的设定当作初始状态传给monstor,名字为sample monstor,防御10,攻击10,生命100

1.先导入lib--luajava-1.1.jar

import org.keplerproject.luajava.LuaState;
import org.keplerproject.luajava.LuaStateFactory;

public class Load{
LuaState luaState;
/**
* Constructor
* @param fileName File name with Lua .
*/
Load(final String fileName) {
this.luaState = LuaStateFactory.newLuaState();

this.luaState.openLibs();
   this.luaState.LdoFile(fileName);

}
/**
* Ends the use of Lua environment.
*/
void close() {
this.luaState.close();
}
/**
* Call a Lua inside the Lua to insert
* data into a Java object passed as parameter
* @param Name Name of Lua .
* @param obj A Java object.
*/
void run(String Name, Object obj) {
this.luaState.getGlobal(Name);
this.luaState.pushJavaObject(obj);
this.luaState.call(1,0);
}
}


public class Monster{
/* Info */
protected String race;
protected int defense;
protected int attack;
protected int life;
/* */
private Load ;
public Monster(String race) {
/* Loads Lua for this race.*/
this. = new Load(race+".lua");
/*Call Lua create .*/
.run("create", this);
}

public void setRace(String race) {
   this.race = race;
}
public String getRace() {
return race;
}
public int getDefense() {
return this.defense;
}
public void setDefense(int defense) {
this.defense = defense;
}
public int getLife() {
return this.life;
}
public void setLife(int life) {
this.life = life;
}
public void setAttack(int attack) {
this.attack = attack;
}
public int getAttack() {
return this.attack;
}
}


monstor.lua---

function create(monster)
monster:setRace("Sample Monster")
monster:setDefense(10)
monster:setAttack(10)
monster:setLife(100)
end


但总是抛出这个错误:

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

不知为何,以后用到的时候再research.

已经查出来,原来在Monster类中少了个方法:

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

怪不得会找不到,

要在一lua文件a.lua里导入其他的lua文件b.lua,用require "b"

如果要从lua中运算后得到返回参数,则需要做一下修改:在lua文件中改成:

function create(monster)
monster:setRace("Sample Monster")
monster:setDefense(10)
monster:setAttack(10)
monster:setLife(100)
return monster
end


在Load.java中的run改成如下:

void run(String Name, Object obj) {
   this.luaState.getGlobal(Name);
   this.luaState.pushJavaObject(obj);
   this.luaState.call(1, 1);// 一个参数,0个返回 
   try {
    Object object =luaState.getObjectFromUserdata(1);
   } catch (LuaException e) {
    e.printStackTrace();
   }
}

你可能感兴趣的:(lua)