Skip to content

Enable the use of __index and __newindex metamethods #1

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Merged
merged 1 commit into from
Feb 24, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion Class.lua
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
sm._class = sm._class or class
local function emptyCtor() end
local function defaultIndex(self, key) return self[key] end
local function defaultNewindex(self, key, value) self[key] = value end

--- Extends the current class function with a callable constructor.
--- <br>The function is backwards compatible with the default implemenation.
Expand All @@ -16,10 +18,29 @@ function class(superType)

function proxy:__call(...)
newType.__init = newType.__init or emptyCtor

if not newType.__indexDefined then
newType.__get = type(newType.__index) == "function" and newType.__index or defaultIndex
newType.__set = newType.__newindex or defaultNewindex
newType.__index = newType
newType.__newindex = nil
newType.__indexDefined = true
end

local instance = newType()
local pInstanceType = sm._class()

function pInstanceType:__index(key)
return newType.__get(instance, key)
end

function pInstanceType:__newindex(key, value)
newType.__set(instance, key, value)
end

instance:__init(...)

return instance
return pInstanceType()
end

function proxy:__index(key)
Expand Down