1

I'm aware that it is possible to use Java defined static methods in Lua, due to the section "Libraries of Java Functions" on http://luaj.org/luaj/README.html.

However I am struggling to find out how I can use the same for instance methods, I have a shortened example here:

private static class CallbackStore {        
    public void test(final String test) {

    }
}

(I am aware that I can use a static method here as well, but it is not possible with the real life scenario)

I am using the following Lua code:

-- Always name this function "initCallbacks"

function initCallbacks(callbackStore)
    callbackStore.test("test")
end

Which does not work as it is expecting userdata back, but I give it a string.

And I call the Lua code like this:

globals.load(new StringReader(codeTextArea.getText()), "interopTest").call();
CallbackStore callbackStore = new CallbackStore();
LuaValue initCallbacks = globals.get("initCallbacks");
initCallbacks.invoke(CoerceJavaToLua.coerce(callbackStore));

where the Lua code is returned by codeTextArea.getText()

Bottom line of my question is, how do I make my code running with test as an instance method?

Dagg Nabbit
  • 75,346
  • 19
  • 113
  • 141
skiwi
  • 66,971
  • 31
  • 131
  • 216

1 Answers1

2

When accessing member functions (in Lua objects in general, not just luaj) you have to provide the this argument manually as the first argument like so:

callbackStore.test(callbackStore,"test")

Or, you can use the shorthand notation for the same thing:

callbackStore:test("test")

mtsvetkov
  • 885
  • 10
  • 21
  • Can you please elaborate more and get a working example? – skiwi Aug 11 '14 at 09:05
  • Sorry, I went out for lunch. Upon looking through the question again I noticed something else - you should be calling `test` as `callbackStore:test("test")` - the `:` operator is shorthand for `callbackStore.test(callbackStore,"test")`, so that might be your problem. – mtsvetkov Aug 11 '14 at 09:54
  • I'll try that later once I have time... As I would also need to rebuild some of the code in question. – skiwi Aug 11 '14 at 09:57
  • Thanks a lot! It works now with the `:`-OOP notation, could you please change your answer to what you roughly said in the comment, so i can accept it? – skiwi Aug 11 '14 at 17:33