Exemplo n.º 1
0
        public void Put(LuaValue key, LuaValue val)
        {
            if (key is null || key.IsNil())
            {
                Debug.Panic("table index is nil!");
            }

            if (key.IsFloat() && LuaFloat.IsNaN(key.GetFloatValue()))
            {
                Debug.Panic("table index is Nan!");
            }

            _changed = true;

            LuaInt idx = 0;

            if (key.IsInt())
            {
                idx = key.GetIntValue();
            }
            else if (key.IsFloat())
            {
                if (LuaMath.FloatToInteger(key.GetFloatValue(), out var fi))
                {
                    idx = fi;
                }
            }

            if (idx >= 1)
            {
                var arrLen = Len();
                if (idx <= arrLen)
                {
                    _arr[(int)(idx - 1)] = val;
                    if (idx == arrLen && val.IsNil())
                    {
                        ShrinkArray();
                    }
                    return;
                }

                if (idx == arrLen + 1)
                {
                    if (_map != null && _map.ContainsKey(key.GetIntValue()))
                    {
                        _map.Remove(key.GetIntValue());
                    }

                    if (!val.IsNil())
                    {
                        if (_arr == null)
                        {
                            _arr = new List <LuaValue>();
                        }

                        _arr.Add(val);
                        ExpandArray();
                    }

                    return;
                }
            }

            if (!val.IsNil())
            {
                if (_map == null)
                {
                    _map = new Dictionary <object, LuaValue>();
                }

                _map[key.GetValue()] = val;
            }
            else
            {
                _map.Remove(key.GetValue());
            }
        }