javalualua-userdata

Add a method to userdata


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


Solution

  • 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
    }