使用 Lua 遍历 Java HashMap 的 Foreach 循环。

我是Lua的新手,我使用LuaJava在我的Java代码上运行,但我卡在尝试在Lua中插入foreach循环以在hashmap中运行中。

在我的Java代码中,我有以下内容:

Java

public class EntityManager {

    public static EntityManager EntityManager = new EntityManager();

    private Map<Integer, Entity> entities = new HashMap<Integer, Entity>();

    public Map<Integer, Entity> entities() {
        return entities;
    }
        ....
}

public class Entity {
    private int id;
    ....
    public int getId() {
        return id;
    }

    public EntityManager getManager() {
        return EntityManager.EntityManager;
    }
}

然后,我有我的Lua脚本,我正在尝试找出如何迭代管理器中hashmap的所有实体:

Lua

owner = {} -- I set this to an Java object that is a child of the Entity class
function doSomeStuff()
    for i, e in pairs(owner:getManager():entities()) do
        if (e:getId() ~= owner:getId()) then
            -- Do some stuff here
        end
    end
end

我几乎已经设置好了我所需要的所有函数等,但我不知道如何创建Java foreach循环的Lua等效循环,以在我的Lua脚本中迭代我的Java hashmap。

此外,我想知道如何检查Lua中的对象类型,以查看它是否为我的Java类之一的实例。例如,在Java中,如果我想查看对象是否为对象类型,我将执行以下操作:

Entity e;
....
if (e instanceof EntityTypeA) {
    // e is of Entity type A
} else if (e instanceof EntityTypeB)
    // e is of Entity type B
}

哦,我不完全确定我传递到Lua脚本中的Java对象是否保留其Java类类型,也不知道如何执行此类操作。

顺便说一下,我正在使用Kepler Project的[LuaJava](http://www.keplerproject.org/luajava/index.html)。

谢谢。

点赞