Beispiel #1
0
    static void Interactive(Squirrel v)
    {
        // print version information
        PrintVersionInfo();

        // add "quit()" function
        v.PushRootTable();
        v.PushString("quit", -1);
        v.NewClosure(Quit, 0);
        v.SetParamsCheck(1, null);
        v.NewSlot(-3, false);

        for (;;)
        {
            int    blocks  = 0;
            bool   str     = false;
            bool   retVal  = false;
            bool   execute = false;
            string buffer  = string.Empty;
            Console.Write("\nsq>");

            while (!execute)
            {
                var c = (char)Console.Read();

                switch (c)
                {
                case '\r': continue;

                case '\n':
                    if (buffer.Length > 0 && buffer.Last() == '\\')
                    {
                        buffer = buffer.Remove(buffer.Length - 1);
                        continue;
                    }
                    if (blocks == 0)
                    {
                        execute = true;
                    }
                    break;

                case '}':
                    if (!str)
                    {
                        blocks--;
                    }
                    break;

                case '{':
                    if (!str)
                    {
                        blocks++;
                    }
                    break;

                case '"':
                case '\'':
                    str = !str;
                    break;
                }

                buffer += c;
            }

            if (!string.IsNullOrEmpty(buffer))
            {
                if (buffer.StartsWith("="))
                {
                    buffer = $"return ({buffer.Substring(1)})";
                    retVal = true;
                }

                int oldtop = v.GetTop();
                if (v.CompileBuffer(buffer, buffer.Length, "interactive console", true) >= 0)
                {
                    v.PushRootTable();
                    if (v.Call(1, retVal, true) >= 0 && retVal != false)
                    {
                        Console.WriteLine();
                        v.PushRootTable();
                        v.PushString("print", -1);
                        v.Get(-2);
                        v.PushRootTable();
                        v.Push(-4);
                        v.Call(2, false, true);
                        retVal = false;
                        Console.WriteLine();
                    }
                }

                v.SetTop(oldtop);
            }
        }
    }