c#将方法注册到lua中&& lua访问C#

还是上一篇的环境。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LuaInterface;

namespace cs2lua
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建lua的解释器
            Lua lua = new Lua();

            //直接运行
            //lua.DoString("num=2");
            //lua.DoString("score=99");
            //Object[] vals = lua.DoString("return num,score");
            //foreach (object obj in vals)
            //{
            //    Console.WriteLine(obj);
            //}


            //执行已经存在的lua脚本
            //lua.DoFile("myLua");


            //////
            ///把一个c#方法注册到lua的一个全局方法中去
            /////

            //一个类的普通方法注册进去
            //lua.RegeisterFunction("NormalMethod",obj,obj.getType().getMethod("NormalMethod")
            Program p = new Program();
            //注意是public权限
            //lua中的名字,  对象, 方法名字
            //lua.RegisterFunction("LuaMethod", p, p.GetType().GetMethod("CLRMethod"));
            //lua.DoString("LuaMethod()");
            //把一个类的静态方法注册进去
            //lua.RegisterFunction("LuaStaticMethod", null, typeof(ClassName).GetMethod("StaticMethod"));
            lua.RegisterFunction("MyStaticMethod", null, typeof(Program).GetMethod("MyStaticMethod"));
            lua.DoString("MyStaticMethod()");

            Console.ReadKey();
        }/*
            lua  与      c# 对应的类型
            nil         null
            string      system.string
            number      system.double
            boolean     system.Boolean
            table       LuaInterface.LuaTable
            function    LuaInterface.LuaFunction
         */ 
         public void CLRMethod()
         {
            Console.WriteLine("Normal");
         }
        public static void MyStaticMethod()
        {
            Console.WriteLine("Static");

        }
    }
}

Lua

require "luanet"
luanet.load_assembly("System")
luanet.load_assembly("cs2lua")

Int32=luanet.import_type("System.Int32");	 
Program=luanet.import_type("cs2lua.Program");

program1=Program();

print(program1.name);
program1:TestMethod();


猜你喜欢

转载自blog.csdn.net/qq_33951440/article/details/79976601
今日推荐