Skip to content

[ENH] Add LuaObject(UserData) #1

@JenyaRostov

Description

@JenyaRostov

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:

  1. Create metatable using lua.CreateMetatable using name from [UserData] attribute
  2. Write TypeName, TypeId from CreateMetaTable and Type to internal Dictionary
  3. Get all static methods with signature int (ILua lua) and [MetaMethod] attribute from the class and push them as metamethods
  4. Create table and push all static methods with the same signature but without [MetaMethod] attribute
  5. 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

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions