Save-Point
FixedArray - Printable Version

+- Save-Point (https://www.save-point.org)
+-- Forum: Material Development (https://www.save-point.org/forum-8.html)
+--- Forum: Scripts Database (https://www.save-point.org/forum-39.html)
+--- Thread: FixedArray (/thread-8438.html)



FixedArray - kyonides - 12-31-2021

FixedArray

The Array With a Fixed Size
for XP VX & ACE


Have you ever wanted to keep a Ruby Array at a certain size? Thinking
Was it a pain you know where to prevent it from ever increasing its size or length? Happy with a sweat

Now you should not worry about that anymore! Grinning

Even so you can still clear its contents at any given time. Winking

The Scriptlet

Code:
# * FixedArray
#   2022-01-11

# Have you ever wanted to keep a Ruby Array at a certain size?
# Was it a pain you know where to prevent it from ever increasing
# its size or length?
# Now you should not worry about that anymore!
# Even so you can still clear its contents at any given time.

# Examples:

# ary = FixedArray.new(3)
# returns: []

# ary = FixedArray.new(3, :a, :b, :c, :d)
# returns: [:a, :b, :c]

class FixedArray < Array
  def initialize(total, *args)
    @maxsize = total > 0 ? total : 0
    concat args.take(@maxsize)
  end
  def push(elem) size == @maxsize ? self : super(elem) end
  def <<(elem) size == @maxsize ? self : super(elem) end
  def unshift(elem) size == @maxsize ? self : super(elem) end
  def +(ary) dup.concat ary.take(@maxsize - size) end
  alias :>> :unshift
  attr_accessor :maxsize
end


Script Calls

You may use p or print or puts or msgbox or msgbox_p script calls depending on your debugging needs and RM version.

Actually >> is an alias of the unshift method.

Code:
array = FixedArray.new(3)
# returns: []
p array.size
# returns: 0
p array.maxsize
# returns: 3
array << :b << :c
# returns: [:b, :c]
array >> :a
# returns: [:a, :b, :c]
array = FixedArray.new(3, :a, :b, :c, :d)
# returns: [:a, :b, :c]
p array.size
# returns: 3
p array.maxsize
# returns: 3


Terms & Conditions

You may include my nickname if you want. Winking
It's free as in beer Beer and speech! Shocked


RE: FixedArray - kyonides - 01-13-2022

Minor Update
During my playtesting of the KPartyActors and KBankai XP scripts, I noticed something curious.
Mad Scientist My scriptlet above did not return a FixedArray object but a mere Array whenever people had added some foreign array to the FixedArray list.

Usually nobody would mind about it for it will still behave like an array, right? Happy with a sweat

The problem was that it would no longer care about the maxsize limitation I had implemented in my custom Baby child class. Laughing

I have finally figured out what I had to do so I have come back to share it will our beloved audience. Grinning

I know, I know. This is a Sculptor scripting tool and nothing else but who knows? Some day it might help some people keep stuff in check. Laughing