Description
I want to add easy UserData support to GmodDotNet
LuaObject is a inheritable class that allows to push and pop c#-style userdata. It already implements some basic metamethods such as __gc and __tostring, with virtual methods Destroy and Name for child classes to override.
At the module startup, every class inherited from LuaObject and with [UserData(string Name)] attribute would be registered.
Registering luaobject consists of steps:
- Create metatable using
lua.CreateMetatable using name from [UserData] attribute
- Write TypeName, TypeId from
CreateMetaTable and Type to internal Dictionary
- Get all static methods with signature
int (ILua lua) and [MetaMethod] attribute from the class and push them as metamethods
- Create table and push all static methods with the same signature but without
[MetaMethod] attribute
- Make new table an
__index for metatable
Usage
Creating LuaObject
[UserData(Name = "MyLuaObject")]
public class MyLuaObject : LuaObject<MyLuaObject>
{
public override string Name() => "MyLuaObject";
public override void Destroy() => Console.WriteLine("Garbage collected!");
public int SomeInt = 5;
private static int ReturnNumber(ILua lua)
{
var self = Pop(lua);
lua.PushNumber(self.SomeInt);
return 1;
}
}
Pushing and poping
int SomePushLuaMethod(ILua lua)
{
MyLuaObject obj = new MyLuaObject();
obj.Push(lua);
return 1;
}
int SomePopLuaMethod(ILua lua)
{
MyLuaObject obj = MyLuaObject.Pop(1); // Pop first argument
Console.WriteLine(obj.SomeInt);
}
Usage in lua is as follows:
local myObj = SomePushLuaMethod()
print(myObj:ReturnNumber())
SomePopLuaMethod(myObj) -- 5 in console
myObj = nil --__gc would be called, also calling Destroy virtual method
Description
I want to add easy UserData support to GmodDotNet
LuaObjectis a inheritable class that allows to push and pop c#-style userdata. It already implements some basic metamethods such as__gcand__tostring, with virtual methodsDestroyandNamefor child classes to override.At the module startup, every class inherited from
LuaObjectand with[UserData(string Name)]attribute would be registered.Registering luaobject consists of steps:
lua.CreateMetatableusing name from[UserData]attributeCreateMetaTableand Type to internal Dictionaryint (ILua lua)and[MetaMethod]attribute from the class and push them as metamethods[MetaMethod]attribute__indexfor metatableUsage
Creating LuaObject
Pushing and poping
Usage in lua is as follows: