Home > Blockchain >  why are there no objects added to my table
why are there no objects added to my table

Time:11-04

I'm working on a lua script where I need a list of buttons to display. I have the following method to add a button to the list buttons:

function addButton(name, text, func, activeColor, passiveColor, xmin, xmax, ymin, ymax, type)
    buttons[name] = {}
    buttons[name]["text"] = text
    buttons[name]["func"] = func
    buttons[name]["active"] = false
    buttons[name]["activeColor"]  = getColorOrDefault(activeColor, ACTIVECOLORDEFAULT)
    buttons[name]["passiveColor"] = getColorOrDefault(passiveColor, PASSIVECOLORDEFAULT)
    buttons[name]["xmin"] = xmin
    buttons[name]["xmax"] = xmax
    buttons[name]["ymin"] = ymin
    buttons[name]["ymax"] = ymax
    buttons[name]["type"] = type
    print("added: "..table.getn(buttons))
end

This function is called twice to add 2 buttons, but the output is:

added: 0
added: 0

what could be a reason my elements are not added to the table?

CodePudding user response:

They're being added--You're just using the wrong method to detect them.

As you can read about in this question, using table.getn only returns the amount of array slots (numeric indexes, such as buttons[0] or buttons[23]. Note that this only counts as an array slot if there are no null indexes in between buttons[1] and buttons[23]!

Using this debugging code, we'll see that your items are indeed being added to the buttons table:

for name, button in pairs(buttons) do
    print(name, button)
end

This is also how you'd get a list of your buttons :-)

  • Related