lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Jul 29, 2017 7:37 AM, "AndreyCh" <sofandr2@gmail.com> wrote:
Hi all

Help me get the number of items in the table

Lua 5.1

-- https://codereview.stackexchange.com/questions/14236/very-basic-chatbot

local messages = {
    [1] = "Hello stranger!",
    ["name"] = "I'm Bob, the owner of this little shop.",
    ["job"] = "I sell stuff.",
    ["hat"] = {
         [1] = "You like my hat?",
         ["yes"] = "It's nice I know.",
         ["no"] = "You ...!",
    },
}
local topic = messages;

print(">>",#topic); -- 1

The result is 1
But I need that result be 4


Thank you



The result is 1 because # is meant to be used with sequences. It gives you some n for which key n+1 is absent.

To count the number of items in a non-sequential table, use pairs() to loop over them and count.