Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to register a C# class constructor in Lua

Tags:

c#

lua

nlua

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?

like image 304
infernalcucumber Avatar asked Mar 10 '26 22:03

infernalcucumber


1 Answers

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()
like image 138
Nikita Avatar answered Mar 12 '26 12:03

Nikita



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!