2

I am trying to add a method to an existing userdata like this, this however game me an error.

local userData = luajava.newInstance("Objects.Block") --creates a userdata from a Java class
userData.newMethod = function()
        -- Do stuff
end

I found this example on a site but it doesn't work either

local userData = luajava.newInstance("Objects.Block")
local mt = getmetatable(userData)
mt.__index.newMethod = function()
        -- Do stuff
end

is there a working way to add a method/function to an existing userdata from Lua

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Timotheus
  • 2,250
  • 5
  • 29
  • 39

1 Answers1

5

The second method you posted will work if the userdata already has a metatable with a table assigned to the __index field. A metatable cannot be assigned to a userdata from Lua for safety reasons. So, you must assign the userdata a metatable from your Java binding code.

lua_newuserdata(L, SOME_SIZE);
luaL_newmetatable(L, "userData.mt");
lua_setmetatable(L, -2);

If the metatable does not already have an __index table, then create one.

local mt = getmetatable(userData)
mt.__index = {
    newMethod = function()
        print('It works!')
    end
}
Judge Maygarden
  • 26,961
  • 9
  • 82
  • 99