سؤال

I'm really stuck at this, searched my ass of google definitely, trying to "import" a table from lua to an array in java with luajava... Now, I've been able to do some easy stuff, printing lua-vars in java and reading a single element from a table.. everything working here

JAVA

LuaState L = LuaStateFactory.newLuaState();
L.openLibs();
L.LdoFile("data/test.lua");
L.getGlobal("x"); //I want to read lua-variable x
LuaObject obj = L.getLuaObject(L.getTop()); //So I get the top-element here
System.out.println(obj.getField("Version")); 

LUA

    x = { ["Version"] = 1.3,["Scans"] = 3 }

Now, this is obviously fairly easy for retrieving single values, but I'd like to get the whole object into Java (as an array or whatever) so I can do some stuff with it.. I tried looping through that LuaObject but since it's not iterable or a 'real' array yet, thats not possible.. Simply outputting obj will tell me its a lua table, I've tried a lot of stupid stuff with .getObject, no success. Then I read something about proxies and .pcall (That looked like it was for passing values in Java to functions in lua, which is not, what i want) Couldnt find anything in the (very very poorly) documented javadoc, so I'm hoping someone has experience with this.. Probably really easy one but hard to find information on. Really happy about any information on this!

p.s. I CANNOT change the original lua file (later on) but that file will only contain one big table..

هل كانت مفيدة؟

المحلول

Lua is a dynamic language, with table being its only data structure. A table can contain any combination of key/value pairs, which is in contrast with Java's static typing. Therefore you need to create a conversion function which will create a Java object from Lua table. This is not provided by LuaJava automatically.

If you want to fill in a Java POD class with data taken from a Lua table, you basically have these options:

  1. Do it manually (easiest) - create a simple function, which takes a Lua stack index, expects a Lua table at that index, and then creates a Java instance of your POD class and fills it with data manually, i.e. you need to type in all the required getField calls.

  2. Use Java reflection (more generic) - the conversion function takes a Lua stack index and a Java Class, creates a new instance of that class and use Java reflection together with lua_next to iterate over the Lua table and fill out the necessary Java fields.

If you only intent to use conversion on one type of Lua table, I suggest you use the first option. The downside is that everytime you change structure, you have to update the conversion code. There are downsides to the second approach as well, for example how should you handle cases of missing/extra keys, subtables etc.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top