Question about functions in tables

This is a pretty noob question lol because I’ve never really scripted this way, but is it alright to do something like putting a function inside of a table, such as:

local module = {}

function Destroy(Part)
    Part:Destroy()
end

function Upgrade(Id)
    print(Id.." was upgraded!")
end


function module.Create(Id)
     local NewEntity = Instance.new("Part", game.Workspace)
     return {Destroy = function() Part:Destroy(NewEntity) end, Upgrade = function() Upgrade(Id) end}
end

return module

Would putting functions in a table like I just did slow it down at all?

Yes. The same way it’s okay to put values in a table, functions can be included. Remember that function values are equivalent to other values (string, bool, number, etc). A function, after all, is a block of code assigned to a variable that can be called, in which the code inside the function runs.

2 Likes

Do you think it would be more efficient and faster (for the game) to use a Id based system and do module.Destroy(Id) (meaning that function is out of the table) instead of having functions inside of a table?

If the function is outside of the table and somewhere else in the module, you won’t even be able to call it. It’d only be able to be called internally within an environment where that variable resides on.

A module should typically include reusable functions or storage of certain variables. So your module can be like

local module = {}

function module.Destroy(arg)
    -- code
end

No I know that, I’m just wondering if it would cause lag to store functions in tables when I’m making a lot of those tables basically.

Not really. I can only assume the difference would be a couple bytes.

Alright thank you very much for your help! I’ve been trying to find new ways to tidy up some code.

Well basically what you’re trying to do is make a library - which works perfectly fine in Roblox. It’s practically the same as the built-in libraries such as ‘math’ or ‘table’.

Performance shouldn’t be an issue. Indexing things within tables isn’t intensive, and if you are doing it a lot, you can probably optimise it or change what you are doing. Even a small performance dip may be worth the readability and whatever the other positives are.

Object oriented programming (in Lua it’s a combination of tables and metatables and functions and properties within tables), which is crazy intensive compared to this, also works fine in Roblox.

1 Like

If you’re worried about performance, make them local functions instead. Local variables are accessed much faster than globals.

For example:

local function Destroy(Part)
    Part:Destroy()
end

That being said, you wouldn’t really notice a difference unless the function is being heavily accessed every second (like thousands of times).

5 Likes