xLua 学习入门使用

127 阅读2分钟

xLua 学习入门使用,学习记录

1. xLua 简介

xLua 是 Unity3D 的一个插件,用于在 Unity3D 中使用 Lua 语言。 支持 iOS、Android、Windows、Mac、Linux、WebGL等平台。

xLua 使用

首先下载xLua源码,github地址

也可以使用git直接下载

git clone https://github.com/Tencent/xLua.git

然后将下载到的文件夹里的 Assets 文件夹拷贝到自己的项目中,等待编译完成即可使用。

单例封装Lua代码运行调用接口

using UnityEngine;
using UnityEngine.Windows;
using XLua;

namespace _Script.Tool
{
    /// <summary>
    /// lua运行单例类,用于运行lua代码
    /// </summary>
    public class XLuaEnv
    {
        #region SinglePattern

        private XLuaEnv()
        {
            env = new LuaEnv();
            env.AddLoader(PjLoader);
        }

        private static XLuaEnv _instance = null;

        /// <summary>
        /// 单例外部调用接口
        /// </summary>
        public static XLuaEnv Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new XLuaEnv();
                }

                return _instance;
            }
        }

        #endregion

        #region Loader

        private LuaEnv env = null;

        public byte[] PjLoader(ref string filePath)
        {
            string path = Application.dataPath;
            path = path.Substring(0, path.Length - 7) +
                   "/DataPath/Lua/" +
                   filePath + ".lua";

            if (File.Exists(path))
            {
                return File.ReadAllBytes(path);
            }

            return null;
        }

        #endregion

        #region Free LuaEnv

        public void Free()
        {
            env.Dispose();
            _instance = null;
        }

        #endregion

        #region Run Lua

        /// <summary>
        /// 运行lua代码对外接口
        /// </summary>
        /// <param name="code">输入的Lua代码</param>
        /// <returns> 返回的结果 </returns>
        public object[] DoString(string code)
        {
            return env.DoString(code);
        }

        #endregion
    }
}

2. Lua 调用静态类

using System;
using _Script.Tool;
using UnityEngine;

namespace _Script.C2L
{
    public static class TestStatic
    {
        public static int ID = 99;

        public static string Name { get; set; }

        public static string Output()
        {
            return "Static";
        }

        public static void Default(string str = "Abc")
        {
            Debug.Log(str);
        }
    }

    public class LuaCallStatic : MonoBehaviour
    {
        private void Start()
        {
            XLuaEnv.Instance.DoString("require 'C2L/LuaCallStatic'");
        }

        private void OnDestroy()
        {
            XLuaEnv.Instance.Free();
        }
    }
}
print("id = " ..  CS._Script.C2L.TestStatic.ID)

-- 给静态变量赋值
CS._Script.C2L.TestStatic.Name = "admin"
print("name = " ..  CS._Script.C2L.TestStatic.Name)

-- 调用静态方法
print( CS._Script.C2L.TestStatic.Output())

CS._Script.C2L.TestStatic.Default()
CS._Script.C2L.TestStatic.Default("def")

Lua 相关

语言内置模式匹配;

闭包(closure);

函数也可以看做一个值;

提供多线程(协同进程,并非操作系统所支持的线程)支持;

数据类型

number

string

boolean

nil

function

table

userdata

thread

ipairs 和 pairs 区别

闭包

函数内返回函数

向上寻找上值

表 table

大G表

总表,也是一个Table(所有变量存储其中)

协程

元表

co = coroutine.create(function()
    while true do
        print("coroutine")
        coroutine.yield()
    end
end)

coroutine.resume(co)

实现面向对象

使用表 表现 类的特性

使用 .调用函数 和 : 调用函数区别

:默认 传入 self

封装

Object = {}
Object.id = 0

function Object:new()
    local o = {}
    setmetatable(o, self)
    self.__index = self
    return o
end

local o = Object:new()
print(o.id)

继承

function Object:subClass(className)
    _G[className] = {}
    local class = _G[className]
    self.__index = self

    setmetatable(class, self)
end

Object:subClass("Test" )
Test.mm = function()
    print("123123")
end

t =  Test:new()
t.mm()

Test:subClass("Test2")
t2 = Test2:new()
t2.mm()

多态

Object = {}
Object.id = 1

function Object:new()
    local o = {}
    setmetatable(o, self)
    self.__index = self
    return o
end

function Object:subClass(className)
    _G[className] = {}
    local class = _G[className]
    self.__index = self
    class.base = self -- 保存父类
    setmetatable(class, self)
end

Object:subClass("Test" )

function Test:ctor()
    print("Test:ctor")
end

Test:subClass("Test2")

function Test2:ctor()
    self.base.ctor(self) -- 调用父类的构造函数,这里一定要用 . 而不是 :,然后传入 self
    print("Test2:ctor")
end

t = Test2:new()
t:ctor()

内存回收

test = {id= 1,name = "test"}
test1 = {id= 1,name = "test"}
test2 = {id= 1,name = "test"}
test3 = {id= 1,name = "test"}

print(collectgarbage("count"))
test = nil
test1 = nil
test2 = nil
test3 = nil
collectgarbage("collect")
print(collectgarbage("count"))

有自动GC的机制