通用(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