Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Metatable constructor: self is nil?

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.

1 comment

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

1 answer

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.

This discussion is preserved as it was. New answers, comments, and votes are closed.