javalualuaj

LuaJ Iterate over Object Array in Coerced Java Object


I'm working with LuaJ 3.0.1 and am having issues iterating over an array contained in a coerced Java object in my Lua script. Currently, here's what I'm doing:

I have a Java class that contains an array of objects. Something like

public class Foo {

   public Bar[] bars;

}

I have a LuaFunction that takes Foo as one of its arguments. I call this function, passing an instance of Foo as follows:

luaFunction.invoke(new LuaValue[]{
   CoerceJavaToLua.coerce(fooInstance)
});

However, the problem arises in the Lua script itself, where I need to iterate over the Bar array. I tried using the following code, but this produces an org.luaj.vm2.LuaError with the message "bad argument: table expected, got userdata" on the line containing the ipairs function.

for i,bar in ipairs(fooInstance.bars) do
   ... do stuff with each bar ...
end

It seems that the Bar array does not become a table when the Foo object is coerced to Lua, instead becoming a userdata type. Thus, it cannot be passed to the ipairs function.

Is there any way I can make it so that the Bar array is treated as a table in Lua? Alternatively, are there any options aside from ipairs that would be more appropriate for looping through the array?


Solution

  • The solution, from Egor's comment on my original question, was to use the following code:

    local i = 0
    while fooInstance.bars[i+1] do
    
       i = i + 1
       local bar = fooInstance.bars[i]
    
       ... do stuff with bar ...
    
    end