Why do you need to use global functions instead of local when using metatables and OOP?

Why do you need to use global functions instead of local on metatables and OOP? I’m quite confused.


function FastFood.new()
    local this = { }
    setmetatable(this, FastFood)
    return this

Why use global function?


local Pizza = { }
Pizza.__index = Pizza
setmetatable(Pizza, { __index = FastFood })

^ What is the use of { __ index =FastFood? I don’t understand as well.

This is complicated but please don’t just right away flag my post, you can let other experienced people answer my question. Thank you so much in advance!

The absence of local in the function above, doesn’t really correlate to oop or metatables. it is instead related to the fact that you are putting a function in the FastFood table, and not creating a variable for a function, with some syntax changes its essentially the same as doing FastFood["new"] = function(...) , which in that case there is not point of using local as we are not creating a variable there.


Jaycbee pretty much hits it right but I wanted to point out it’s not a global or local function either, it’s just different syntax for table sets.

Like tab.index = function().

The first part was answered for you, so I’ll answer the second part: why does Pizza get given a metatable where the index is FastFood? For inheritance.

You add a member called __index to the table Pizza but that doesn’t actually get used until your constructor function sets Pizza as the object’s metatable. setmetatable is so that something can have access to another table. When you try access a member (property or method) of an object created by Pizza.new, it searches for the item first in the object, then in Pizza, then in FastFood.

This tutorial could be helpful for you to understand what goes on here:

By the way, you won’t get flagged just for asking a question like this. :slight_smile:


Thanks colbert! I got it. ( 30 characters)

So if let’s say if I use a local function, is it a variable or what?

The syntax goes a bit like this. Each tab has the syntax sugar on top and the equivalent code on the bottom.

Local Functions
local function func_name() end
local func_name
func_name = function() end
Global-ish Functions

Global-“ish” because this will instead set a local variable if one with the same name is already defined.

function func_name() end
func_name = function() end
Table Functions
function Module.func_name() end
Module.func_name = function() end

So yes, local function would be a local variable.


Thank you so much! ( 30 chars)