-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
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.CreateMetatableusing name from[UserData]attribute - Write TypeName, TypeId from
CreateMetaTableand 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
__indexfor 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 methodMetadata
Metadata
Assignees
Labels
No labels