Skip to content

Commit

Permalink
Fix ignoring __index override by derived classes
Browse files Browse the repository at this point in the history
  • Loading branch information
Sainan authored and well-in-that-case committed Jan 17, 2025
1 parent ad25ead commit a6c5519
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 9 deletions.
2 changes: 1 addition & 1 deletion operators.pluto
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ local Pluto_operator_new <const> = function(mt, ...)
end
local t = {}
setmetatable(t, mt)
if not mt.__index or mt.__parent then
if not rawget(mt, "__index") then
mt.__index = mt
end
if mt.__construct then
Expand Down
13 changes: 6 additions & 7 deletions src/lparser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5788,16 +5788,15 @@ static void builtinoperators (LexState *ls) {
ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "mt")));
ls->tokens.emplace_back(Token(')'));

// if not mt.__index or mt.__parent then
// if not rawget(mt, "__index") then
ls->tokens.emplace_back(Token(TK_IF));
ls->tokens.emplace_back(Token(TK_NOT));
ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "rawget")));
ls->tokens.emplace_back(Token('('));
ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "mt")));
ls->tokens.emplace_back(Token('.'));
ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "__index")));
ls->tokens.emplace_back(Token(TK_OR));
ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "mt")));
ls->tokens.emplace_back(Token('.'));
ls->tokens.emplace_back(Token(TK_NAME, luaX_newliteral(ls, "__parent")));
ls->tokens.emplace_back(Token(','));
ls->tokens.emplace_back(Token(TK_STRING, luaX_newliteral(ls, "__index")));
ls->tokens.emplace_back(Token(')'));
ls->tokens.emplace_back(Token(TK_THEN));

// mt.__index = mt
Expand Down
28 changes: 27 additions & 1 deletion testes/pluto/basic.pluto
Original file line number Diff line number Diff line change
Expand Up @@ -2853,7 +2853,7 @@ do
local p = new Player("John")
assert(p.name == "John")
end
-- Class overriding '__index'
-- Overriding '__index'
do
$define extraOffset = 10

Expand All @@ -2880,6 +2880,32 @@ do
c.num = 42
assert(c.num == 42)
end
do
local class Base
base_member = 1
end

local Derived
class Derived extends Base
derived_member = 2

function __index(key)
if key == "magic" then
return 3
end
return Derived[key]
end
end

local inst = new Derived()
assert(inst.base_member == 1)
assert(inst.derived_member == 2)
assert(inst.magic == 3)
inst.derived_member += 10
inst.user_defined = 4
assert(inst.derived_member == 12)
assert(inst.user_defined == 4)
end
-- Metamethod inheritance
do
local class Base
Expand Down

0 comments on commit a6c5519

Please sign in to comment.