how to register a C# class constructor in Lua

446 views Asked by At

I'm using a c# class:

public class TestClass
    {
        int _a;
        public void Set(int a)
        {
            _a = a;
        }
        public void Print()
        {
            Console.WriteLine(_a);
        }
    }

and register it:

Lua lua = new Lua();
lua["Debug"] = new TestClass();
lua.DoFile("script.lua");

and call it from script next way:

a=Debug
a:Set(5)
a:Print()

What should I change/add to use constructor with parameters?

1

There are 1 answers

0
Nikita On BEST ANSWER

First off, you need to import corresponding namespace where your class TestClass is located to use it from lua script:

namespace Application
{
    public class TestClass
    {
        int _a;

        public void Print()
        {
            Console.WriteLine(_a);
        }

        public TestClass(int a)
        {
            this._a = a;
        }
    }
}

Lua lua = new Lua();
lua.LoadCLRPackage();
lua.DoFile("script.lua");

Now you will be able to instantiate TestClass from script.lua file:

import ('Application')
a=TestClass(5)
a:Print()