0
votes

A method in java returns an Array, and I want to manipulate the information from that array in Lua but it seems that Lua doesn't convert arrays to tables as I'd hoped.

Is there a way to do this?

For example I have this method in Java:

public Node[] getChildren(){
     return children.toArray(new Node[children.size()]);
}

When I call this function from Lua I can't do anything with it or have to Instance it, iterate trough it and copy everything to a Lua-Table and then use it. Is there a way to convert the Array to a Lua-Table in Java and then return that?

EDIT: I use LuaJ and the LuaJava library.

1
Stating what Lua-in-Java package (or vice versa) you're using might prove helpful. Anyway in Lua arrays are just tables (which happen to have consecutive integer keys only, and indexing starts at 1).jpjacobs
Well I put that info in the tags which might not have been the best idea. Anyway: I'm using LuaJ with the LuaJava library.Timotheus

1 Answers

3
votes

From the LuaJava manual, it appears that you have to manipulate the proxy objects returned by Java using their Java methods (using Lua's colon syntax for object-oriented calls, ie my_proxy_array_list:get(5)).

It doesn't describe any built-in translation of Arrays to tables, so if you need to construct a table from a Java Array (say, because you want to run a function from Lua's table library on it), you'll have to iterate over the Array (using your knowledge of Java to do that) and put the value of each Array index into the corresponding table index.

If, however, you just need something that works like a Lua table, you can make something in Lua with a metatable with functions that translate __index and __newindex into the appropriate Java methods (probably get and set), like this:

local wrap_lj_proxy; do
  local proxy_mt = {}

  function proxy_mt:__index(k)
    return self.proxy:get(k)
  end

  function proxy_mt:__newindex(k,v)
    return self.proxy:set(k,v)
  end

  function wrap_lj_proxy (proxy)
    return setmetatable({proxy=proxy},proxy_mt)
  end
end

With the above you can call wrap_lj_proxy with your ArrayList and get back an object you can index with the index operator:

local indexable = wrap_lj_proxy(myAL)
print(indexable[5]) -- equivalent to myAL:get(5)