Help with making a 'global function'

I want to make a series of functions that can be applied to any object. For example:

local object = Instance.new("Part")

local funcs = {}
function funcs:test() --(I want to be able to use self)
    print(self.Name)
end

object:test()

I tried this with a module and a normal script, but both threw this error:
testfunction

What’s the correct method to achieve this?

1 Like

You will want to wrap it.

local function wrap(instance)
    return setmetatable({ this = instance }, { __index = instance })
end

local wrapped = wrap(Instance.new("Part"))

function wrapped:test()
    print(self.Name)
end

wrapped:test()
1 Like

A global function would probably need to be stored in a module script.


local funcs = {}
local object = Instance.new(“Part”,workspace)
function funcs:test() --(I want to be able to use self)
    print(self.Name)
end
return funcs

And then require it. That should work.

I tried that exact function and it threw the same error

1 Like

Were you looking to do something like this?

1 Like

Yeah, you and @sjr04 got it. I’ve decided against using it though as it really has no functional benefit in rbxlua. It’s fun to play with but decreases efficiency, really just syntactic sugar.