lua-users home
lua-l archive

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


On Sun, 30 Jul 2017 11:44:15 -0400
Rena <hyperhacker@gmail.com> wrote:

> 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.


Thank you.  I already helped :-)


-- by szbnwer
len=function(stuff)
  local typ=type(stuff)
  if typ=='string' then return #stuff
  elseif typ=='table' then
    local l=0
    for _ in pairs(stuff) do
      l=l+1 end
    return l end 
end


-- 
AndreyCh <sofandr2@gmail.com>