0

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?

2
  • local i=0; while fooInstance.bars[i+1] do i=i+1; local bar = fooInstance.bars[i]; ... end Commented Feb 8, 2020 at 9:29
  • @EgorSkriptunoff thanks! That worked perfectly Commented Feb 13, 2020 at 18:47

1 Answer 1

0

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.