Peter Boomsma
Peter Boomsma

Reputation: 9808

How to iterate through results in sets?

In my Tabletop Simulator mod I have a bag, when something is dropped in the bag the emptyContents() function is called. For example I can drop 15 dice in the bag.

In the emptyContents() function I iterate over the objects in the bag. But as you can see I have to put in multiple if statements to catch the amount of dice put in because I want the dice to be spawned on different positions.

The contents variable is the amount of dice in the bag.

function emptyContents()
    contents = self.getObjects()

    for i, _ in ipairs(self.getObjects()) do
      if i <= 6 then
        self.takeObject(setPosition(5, -3))
      elseif i <= 12 then
        self.takeObject(setPosition(12.4,-5))
      elseif i <= 18 then
        self.takeObject(setPosition(19.8,-7))
      end
    end
end

How can I make the function less static? Because now I need to write if statements for each set of 6 dice.

Upvotes: 0

Views: 185

Answers (1)

上山老人
上山老人

Reputation: 462

maybe you can add a config like this:

local t = {
    {6, 5, -3},
    {12, 12.4, -5},
    {18, 19.8, -7},
}

function emptyContents()
    contents = self.getObjects()

    for i, _ in ipairs(self.getObjects()) do
        for _, v in ipairs(t) do
            local l, p1, p2 = unpack(v)
            if i <= l then
                self.takeObject(setPosition(p1, p2))
                break
            end
        end
    end
end

Upvotes: 1

Related Questions