Open Arrays or ArrayLists in Lua (Convert array to table)

你离开我真会死。 提交于 2019-12-04 22:23:28

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)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!