通用(Lua):Unity3D中使用Lua的實現


最近在用unity3D做網游,客戶端需要用到lua腳本來實現任務系統。

考慮到跨平台性,選擇了:KopiLua。(在開源社區里有下載)

經測試,在web,iso,android,pc均能正常使用。

只是在使用DoFile讀取lua腳本的時候,里面包涵中文變量的時候會出錯;
所以我改了下它的讀取。
要求lua文件格式為UTF8無rom的格式。
然后由於涉及文件很長,是一段一段的讀取,所以截斷的時候,有可能恰好截斷了中文字符,所以寫了個 checkUTF8_CJK()方法來處理截斷中文字符的情況;
具體實現,都在代碼里,有很清楚的注釋就不多說了。

//這是我修改后的讀取方法
public static int fread(CharPtr ptr, int size, int num, Stream stream)
        {
            int num_bytes = num * size;
            byte[] bytes = new byte[num_bytes];
            try
            {
                int result = stream.Read(bytes, 0, num_bytes);
                result = checkUTF8_CJK(stream, bytes, result);//檢測截斷的問題
                char[] UTF8Chars = new char[Encoding.UTF8.GetCharCount(bytes, 0, result)];
                Encoding.UTF8.GetChars(bytes, 0, bytes.Length, ptr.chars, 0);
                result = UTF8Chars.Length;
                return result/size;
            }
            catch
            {
                return 0;
            }
        }

        /// <summary>
        /// 檢測最后的多字節字符是否被截斷;
        /// 若被截斷,則把流退后,下次載讀
        /// </summary>
        private static int checkUTF8_CJK(Stream stream, byte[] bytes, int result)
        {
            //UTF8編碼基本格式
            //第一位總是在 11xx xxxx-1111 1101之間; 其余位在10xx xxxx - 1011 1111之間
            //第一位有幾個一開頭則表示有幾位
            if (bytes[result - 1] >= 128)//最后是多字節字符的某一位
            {
                int bits = 0;
                for (int i = 0; i < 6; ++i)//UTF8一個字符理論最多站6位
                {
                    if (result - 6 <= 0)
                        break;
                    if (bytes[result - i - 1] > 0xfc)
                    {
                        bits = 6;
                    }
                    else if (bytes[result - i - 1] >= 0xf8)
                    {
                        bits = 5;
                    }
                    else if (bytes[result - i - 1] >= 0xf0)
                    {
                        bits = 4;
                    }
                    else if (bytes[result - i - 1] >= 0xe0)
                    {
                        bits = 3;
                    }
                    else if (bytes[result - i - 1] > 0xc0)
                    {
                        bits = 2;
                    }
                    if (bits > 0)//找到了第一位
                    {//如果被中間截斷,則退回去,下次再讀
                        if (bits != i + 1)
                        {
                            stream.Position -= (i + 1);
                            result -= (i + 1);
                        }
                        break;
                    }
                }
            }
            return result;
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM