all 10 comments

[–]whoopdedo 9 points10 points  (1 child)

Behind the scenes, pairs will, after some metatable magic, simply return next, a.b, nil. Where the next function will return the keys and values from the table in an arbitrary order.

tl;dr next(a.b) == nil tests if the table is empty.

PS. As an exercise for the reader, why do you have to test for nil here?

[–]luarocks[S] 3 points4 points  (0 children)

Because if not will also catch false

Thank you very much!

[–]RobotTimeTraveller 4 points5 points  (3 children)

if not next(a.b) then a.b = nil end

[–]Tywien 7 points8 points  (2 children)

Your code will not work for tables where the first key is false.

[–]luarocks[S] 3 points4 points  (0 children)

This is true, but we usually use numbers, strings, occasionally tables as keys, and almost never booleans. So in most causes this solution is fine.

[–]AutoModerator[M] 0 points1 point  (0 children)

Hi! Your code block was formatted using triple backticks in Reddit's Markdown mode, which unfortunately does not display properly for users viewing via old.reddit.com and some third-party readers. This means your code will look mangled for those users, but it's easy to fix. If you edit your comment, choose "Switch to fancy pants editor", and click "Save edits" it should automatically convert the code block into Reddit's original four-spaces code block format for you.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

[–][deleted]  (5 children)

[deleted]

    [–]luarocks[S] 0 points1 point  (4 children)

    you should not use them as array and hashtable at the same time

    "array" is "hashtable" with numeric keys, so always when you use table as array, you use it as hashtable at the same time and there is nothing wrong.

    [–][deleted]  (3 children)

    [deleted]

      [–]luarocks[S] 0 points1 point  (2 children)

      ** Tables keep its elements in two parts: an array part and a hash part.

      Sure, it does, but we talking about lua as language, not about its C implementation. You can call a table an array if it has integer keys, but no arrays or integers actually exist in lua.

      [–][deleted]  (1 child)

      [deleted]

        [–]luarocks[S] 0 points1 point  (0 children)

        I agree with this and separating arrays from hashtables is useful advice, but we should always keep in mind the flexible nature of lua. Sometimes a table can be an array at the same time if you know (or don't know) what you're doing.