Skip to content

Commit e3c2270

Browse files
committed
Automatically create __call metamethods for userdatas with constructors
1 parent f67e9ee commit e3c2270

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

MoonSharp.Interpreter/Execution/VM/Processor/Processor_IExecutionContext.cs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11

2+
using System.Linq;
3+
24
namespace MoonSharp.Interpreter.Execution.VM
35
{
46
sealed partial class Processor
@@ -63,6 +65,32 @@ internal DynValue GetBinaryMetamethod(DynValue op1, DynValue op2, string eventNa
6365

6466
internal DynValue GetMetamethod(DynValue value, string metamethod)
6567
{
68+
if (value.Type == DataType.UserData && metamethod == "__call")
69+
{
70+
var ud = value.UserData;
71+
var desc = ud.Descriptor;
72+
73+
if (desc != null)
74+
{
75+
var ctor = desc.Index(m_Script, ud.Object, DynValue.NewString("__new"), true);
76+
77+
if (ctor != null && !ctor.IsNil())
78+
{
79+
return DynValue.NewCallback((ctx, args) =>
80+
{
81+
var arr = args.GetArray();
82+
83+
if (arr.Length > 0)
84+
{
85+
arr = arr.Skip(1).ToArray();
86+
}
87+
88+
return ctx.GetScript().Call(ctor, arr);
89+
});
90+
}
91+
}
92+
}
93+
6694
if (value.Type == DataType.UserData)
6795
{
6896
DynValue v = value.UserData.Descriptor.MetaIndex(m_Script, value.UserData.Object, metamethod);

0 commit comments

Comments
 (0)