Lua___面向对象的使用案例(XLua)

案例一:创建的类与被创建的类可以互相调用

using System;
using System.Collections.Generic;
using KEngine;
using UnityEngine;
using XLua;

namespace Game.Lua
{
    //核心是LuaTable类,通过Set()绑定,并执行Get()与之绑定的方法
    public class LuaClass
    {
        public LuaFunction AwakeFunction;
        public LuaTable LuaScript;

        public LuaClass(string luaFileName, params object[] arr)
        {
            RegisterToLuaTable(luaFileName);
            if (AwakeFunction != null) AwakeFunction.Call(arr);
        }
        
        /// 
        /// 将C#的方法和属性注到LuaTable中
        /// 
        /// 
        public void RegisterToLuaTable(string lueFileName)
        {
            object[] objects = null;

            objects = LuaManager.Instance.DoString(lueFileName);

            LuaScript = objects[0] as LuaTable;

            if (LuaScript == null)
            {
                Log.Error("lua script no table callback...." + lueFileName);
            }
            else
            {
                LuaScript.Set("class", this);
                LuaScript.Get("Awake", out AwakeFunction);
            }
        }
    }
}
--Class.lua
--创建lua类,每个创建的对象会自动执行Awake()方法

Class = {}

local this = Class

function this:New(className, ...)
    if className == nil then
        Log.Error("Class Constructor Is Error...")
        return nil
    end
    local luaClass = CS.Game.Lua.LuaClass(className, ...)
    this = luaClass.LuaScript
    return this
end
--开始测试

--test1.lua

require('Class')

local this = {}
local test2
function this.Start()
    test2 = Class:New("test2",this) --输出: => test2.Awke()
    test2:Pushtest1() -- 输出:test1方法被调用了
                      -- 过程:New()方法会自动test2的Awake()方法,此时打印“ => test2.Awke()”,接着test2调用了Pushtest1(),而这个里执行的是test1对象的ShowLog()方法,因此打印“test1方法被调用了”
end

function this:ShowLog()
    print("test1方法被调用了")
end

 

--test2

local this = {}
local test1
function this.Awake(...)
    test1 = ...
    print(" => test2.Awke()")
end

function this:Pushtest1()
    test1:ShowLog()
end

 

你可能感兴趣的:(Lua)