Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Metatable constructor: self is nil?

Asked by 2 years ago

I'm new to object oriented programming, and I got a constructor function from the official Lua website. The problem is, when I run this in a Script, it errors, saying that self is nil.

local Account = {}

function Account:new (o)
    o = o or {}   -- create object if user does not provide one
    setmetatable(o, self)
    self.__index = self --Error, self is nil?
    return o
end

return Account

Maybe object oriented programming is different in Roblox.

0
this forum post explains the boilerplate code that is needed for object oriented programming pretty well: https://devforum.roblox.com/t/all-about-object-oriented-programming/8585 OfficerBrah 494 — 2y

1 answer

Log in to vote
0
Answered by 2 years ago

Thanks to https://devforum.roblox.com/t/why-can-i-never-use-self/266827/4, I have fixed this!

When calling module.new(), use module:new() instead.

--What I was trying
local module = require(game.ReplicatedStorage.ModuleScript)

local h = module.new() --Error!

--What worked
local module = require(game.ReplicatedStorage.ModuleScript)

local h = module:new() --It has a : instead of a .

--You could also use
local module = require(game.ReplicatedStorage.ModuleScript)

local h = module.new(module)

Hope this helps anyone who sees this.

Ad

Answer this question